package com.epalmpay.service.weixin.impl;

import com.alibaba.fastjson.JSONObject;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.payplat.*;
import com.epalmpay.service.activity.IRedPackageUserService;
import com.epalmpay.service.app.IAppNoticeService;
import com.epalmpay.service.groupaccount.impl.GroupAccountServiceImpl;
import com.epalmpay.service.posapi.PosApiService;
import com.epalmpay.service.posapi.PosApiServiceTransactional;
import com.epalmpay.service.thread.AfterRebackMoneyThread;
import com.epalmpay.service.weixin.IWxApiMemberService;
import com.epalmpay.status.Rescode;
import com.epalmpay.entity.*;
import com.epalmpay.entity.Response;
import com.epalmpay.enumdef.ActivityEnum;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.mapper.*;
import com.epalmpay.payplat.result.PayResult;
import com.epalmpay.payplat.result.WxTKPayResult;
import com.epalmpay.service.activity.ICouponUserService;
import com.epalmpay.service.management.ITemplateMailSendService;
import com.epalmpay.service.member.IMemberService;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.service.weixin.IWxApiMallService;
import com.epalmpay.util.*;
import com.epalmpay.util.payplat.UtilFun;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * Created by lifayi on 2017/10/12.
 */
@Service
public class WxApiMallServiceImpl implements IWxApiMallService {

	@Resource
	private MainAdvertMapper mainAdvertMapper;
	@Resource
	private MallCategoryMapper mallCategoryMapper;
	@Resource
	private MallEntityGoodMapper mallEntityGoodMapper;
	@Resource
	private OrderGoodMapper orderGoodMapper;
	@Resource
	private OrderGoodItemMapper orderGoodItemMapper;
	@Resource
	private MemberMapper memberMapper;
	@Resource
	private TradeOfflineMapper tradeOfflineMapper;
	@Resource
	private GroupMapper groupMapper;
	@Resource
	private ShopMapper shopMapper;
	@Resource
	private BonusVerifyRuleMapper bonusVerifyRuleMapper;
	@Resource
	private GroupWxconfigMapper groupWxconfigMapper;
	@Resource
	private MemberCardMapper memberCardMapper;
	@Resource
	private MemberAddressMapper memberAddressMapper;
	@Resource
	private BonusVerifyLogMapper bonusVerifyLogMapper;
	@Resource
	private CouponUserMapper couponUserMapper;
	@Resource
	private MallEntityGoodSpecMapper mallEntityGoodSpecMapper;
	@Resource
	private CitiesMapper citiesMapper;
	@Resource
	private MallFreightDetailMapper mallFreightDetailMapper;
	@Resource
	private MallFreightMapper mallFreightMapper;
	@Resource
	private MallCartMapper mallCartMapper;
	@Resource
	private CouponMapper couponMapper;
	@Resource
	private BonusSendRuleMapper bonusSendRuleMapper;
	@Resource
	private BonusSendLogMapper bonusSendLogMapper;

	@Resource
	private BonusVerifyShopMapper bonusVerifyShopMapper;

	@Resource
	private ActivityBaseMapper activityBaseMapper;
	@Resource
	private ICouponUserService couponUserService;
	@Resource
	private IMemberService memberService;
	@Resource
	private IWxApiMemberService wxApiMemberService;
	@Resource
	private GroupAccountServiceImpl groupAccountService;
	@Resource
	private ICouponUserService iCouponUserService;
	@Resource
	private IRedPackageUserService iRedPackageUserService;

	@Resource
	@Lazy
	private ITemplateMailSendService templateMailSendService;
	@Resource
	private CouponGoodsShareMapper couponGoodsShareMapper;
	@Resource
	private CouponActivityShareMapper couponActivityShareMapper;

	@Resource
	private MemberGradeMapper memberGradeMapper;

	@Resource
	private GroupReceiveInfoMapper groupReceiveInfoMapper;
	@Resource
	private ActivityUnroutineRuleMapper activityUnroutineRuleMapper;
	@Resource
	private PosApiServiceTransactional posApiServiceTransactional;

	@Resource
	private IAppNoticeService appNoticeService;

	@Resource
	private IWalletService walletService;

	@Resource
	protected PosApiService posApiService;


	private ExecutorService exec;

	@Value("${PROFIT_URL}")
	private String profiturl;

	@Value("${TRADE_FEE}")
	private String tradefee;

	@PostConstruct
	public void initialize() {
		exec = Executors.newCachedThreadPool();
	}

	private Logger logger = Logger.getLogger(WxApiMemberServiceImpl.class);

	@Override
	public Response advertise(Long groupId) {
		List<Map<String, String>> advertise_img = mainAdvertMapper.listMallAdvertiesByGroupId(groupId);
		return Response.getSuccess(advertise_img);
	}

	@Override
	public Response category(Long groupId) {
		List<Map<String, Object>> shop_categroy_list = mallCategoryMapper.listMallOneLevelCategory(groupId);
		return Response.getSuccess(shop_categroy_list);
	}

	@Override
	public Response recommendGood(Long groupId, Integer pageNo, Integer pageSize) {
		Integer pageStart = (pageNo - 1) * pageSize;
		List<Map<String, Object>> data = mallEntityGoodMapper.listRecommendGoodByGroupId(groupId, pageStart, pageSize);
		for (int i = 0; i < data.size(); i++) {
			Map<String, Object> item = data.get(i);
			String img1 = ((String) item.get("goods_img")).split(",")[0];
			item.replace("goods_img", img1);
		}
		return Response.getSuccess(data);
	}

	@Override
	public Map<String, Object> queryGoodList(Long groupId, Long categoryFirstId, Long categorySecondId, String goodName, Integer sortMethod, Integer pageNo,
			Integer pageSize) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();

		if (groupId == null) {
			throw new ApplicationException(Rescode.FAIL, "groupId 不能为空！");
		}
		if (sortMethod == null) {
			throw new ApplicationException(Rescode.FAIL, "sortMethod 不能为空！");
		}
		if (pageNo == null) {
			throw new ApplicationException(Rescode.FAIL, "pageNo 不能为空！");
		}
		if (pageSize == null) {
			throw new ApplicationException(Rescode.FAIL, "pageSize 不能为空！");
		}

		Map<String, Object> param = new HashMap<String, Object>();
		// 取得门店数据；
		param.clear();
		param.put("groupId", groupId);
		param.put("isLaunch", 1);
		param.put("name", goodName);
		param.put("categoryFirstId", categoryFirstId);
		param.put("categorySecondId", categorySecondId);
		param.put("sortMethod", sortMethod);
		param.put("start", pageSize * (pageNo - 1));
		param.put("limit", pageSize);

		List<MallEntityGood> mallEntityGoods = mallEntityGoodMapper.selectGoodList(param);
		if (mallEntityGoods == null)
			return map;

		List<Map<String, Object>> goodList = new ArrayList<Map<String, Object>>();
		for (MallEntityGood good : mallEntityGoods) {
			Map<String, Object> goodDetail = new HashMap<String, Object>();
			goodDetail.put("goodId", good.getId());
			goodDetail.put("goodPic", good.getPicture());
			goodDetail.put("goodName", good.getName());
			goodDetail.put("salePrice", good.getSalePrice());
			goodDetail.put("promotionPrice", good.getPromotionPrice());
			goodDetail.put("promotionPrice2", good.getPromotionPrice2());
			goodDetail.put("saleNum", good.getSaleNum());
			goodDetail.put("categoryFirstName", good.getCategoryFirstName());
			goodDetail.put("categorySecondName", good.getCategorySecondName());
			goodList.add(goodDetail);
		}
		if (goodList.size() > 0) {
			map.put("goodList", goodList);
		}
		return map;
	}

	@Override
	public Response goodDetail(Long goodId) {
		MallEntityGood mallEntityGood = mallEntityGoodMapper.selectByPrimaryKey2(goodId);
		if (mallEntityGood.getPostMethod() == -2) {
			mallEntityGood.setPostName("自提");
		} else if (mallEntityGood.getPostMethod() == -1) {
			mallEntityGood.setPostName("免运费");
		}

		//获取供货商的联系电话
		Long shopid = mallEntityGood.getShopId();
		if(shopid != null) {//由门店供货
			Shop shop = shopMapper.selectByPrimaryKey(shopid);
			mallEntityGood.setContactPhone(shop.getPhone());
		} else {//由商圈供货
			Long groupid = mallEntityGood.getGroupId();
			Group group = groupMapper.selectByPrimaryKey(groupid);
			mallEntityGood.setContactPhone(group.getPrincipalMobile());
		}

		List<MallEntityGoodSpec> mallEntityGoodSpecList = mallEntityGoodSpecMapper.selectByGoodId(goodId);
		if(mallEntityGoodSpecList != null && mallEntityGoodSpecList.size() > 0) {
			Map<String, String> priceRange = mallEntityGoodSpecMapper.getPriceRangeByGoodId(goodId);
			mallEntityGood.setPriceRange(priceRange.get("priceRange"));
			mallEntityGood.setPrice2Range(priceRange.get("price2Range"));
		}
		mallEntityGood.setMallEntityGoodSpecList(mallEntityGoodSpecList);
		return Response.getSuccess(mallEntityGood);
	}

	@Override
	public Response saveSubmitCart(Long memberId, ArrayList<Long> goodIds) {
		List<MallCart> mallCartList = mallCartMapper.listByMemberIdAndCartId(memberId, goodIds);

		MemberGrade memberGrade = memberGradeMapper.getByMemberId(memberId);

		Long shopId = null;

		List<Map<String, Object>> data = new ArrayList<>();
		for (int i = 0; i < mallCartList.size(); i++) {
			MallCart mallCart = mallCartList.get(i);

			MallEntityGood mallEntityGood;

			if(mallCart.getSpecId() == null) {
				mallEntityGood = mallEntityGoodMapper.selectByPrimaryKey(mallCart.getGoodId());
			} else {
				mallEntityGood = mallEntityGoodMapper.selectBySpecId(mallCart.getSpecId());
			}

			if (mallEntityGood == null) {
				return Response.getError("商品已下架，请重新选择");
			}

			if(i == 0) {
				shopId = mallEntityGood.getShopId();
			} else {
				// 渠道和门店不能同时购买 ，不同门店 也不能同时
				if(shopId!=null&&mallEntityGood.getShopId()==null ){
					return Response.getError("购物车结算,渠道商品和门店商品不能同时购买");
				}
				if(mallEntityGood.getShopId()!=null){
					if( !mallEntityGood.getShopId().equals(shopId)) {
						return Response.getError("购物车结算只能选择同一个门店的商品");
					}
				}
			}

			String goodName = mallEntityGood.getName();
			if (mallEntityGood.getIsLaunch() == 0) {
				return Response.getError("商品 " + goodName + " 已下架，请重新选择");
			}

			if (mallCart.getGoodNumber() > mallEntityGood.getStockNumber()) {
				return Response.getError("商品 " + goodName + " 库存不足，请重新选择");
			} else {
				if (mallEntityGood.getLimitNumber() > 0) {
					long memberHavePurchaseNum = orderGoodItemMapper.countMemberHavePurchase(memberId, mallCart.getGoodId());
					if (memberHavePurchaseNum + mallCart.getGoodNumber() > mallEntityGood.getLimitNumber()) {
						return Response.getError("商品 " + goodName + " 超过最大购买数量，请重新选择");
					}
				}
			}
			Map<String, Object> good = new HashMap<>();
			good.put("id", mallEntityGood.getId());
			good.put("name", goodName);
			good.put("image", mallEntityGood.getPicture().split(",")[0]);
			good.put("goodNum", mallCart.getGoodNumber());
			good.put("salePrice", mallEntityGood.getSalePrice());
			good.put("promotionPrice", mallEntityGood.getPromotionPrice());
			good.put("promotionPrice2", mallEntityGood.getPromotionPrice2());
			good.put("realPrice", memberGrade.getName().equals(BizEnum.MemberGradeDefault.attention.getName()) ?
					mallEntityGood.getPromotionPrice2() : mallEntityGood.getPromotionPrice());
			good.put("spec1_attr", mallEntityGood.getSpec1Name());
			good.put("spec2_attr", mallEntityGood.getSpec2Name());

			data.add(good);
		}
		return Response.getSuccess(data);
	}

	@Override
	public Response availableBenefit(Long memberId, Long goodsId, Integer tradeAmt) throws ParseException {
		Member member = memberMapper.selectByPrimaryKey(memberId);
		MemberGrade memberGrade= memberGradeMapper.selectByPrimaryKey(member.getGradeId());

		MallEntityGood mallEntityGood = mallEntityGoodMapper.selectByPrimaryKey(goodsId);
		BonusVerifyRule bonusVerifyRule=null;
		//积分核销比例  自营商品走渠道的核销比例 门店商品走门店的核销比例
		if(mallEntityGood.getGroupId()!=null && mallEntityGood.getShopId() !=null){
			//门店自己设置
			bonusVerifyRule = bonusVerifyRuleMapper.qyeryShopVerifyRule(mallEntityGood.getShopId());
		}
		if(bonusVerifyRule ==null){
			//自营
			bonusVerifyRule = bonusVerifyRuleMapper.getDefaultByGroupId(member.getGroupId());
		}
//		BonusVerifyRule bonusVerifyRule = bonusVerifyRuleMapper.getDefaultByGroupId(member.getGroupId());
		if (bonusVerifyRule == null) {
			return Response.getError("还未设置积分兑换比例");
		}
		Map<String, Object> entityGoodBonusVerify = mallEntityGoodMapper.getGoodBonusPayMethod(goodsId);
		Map<String, Object> data = new HashMap<>();


		// 积分
		data.put("user_bonus_amount", member.getBonusAmount());
		data.put("bonus_verify_rate", bonusVerifyRule.getVerifyRate());
		data.put("good_detail", entityGoodBonusVerify);
		data.put("dis_count", memberGrade.getDiscountRate());

		// 优惠券
		data.put("can_use_couponList",
				couponUserService.listUserCouponsInfo(memberId, goodsId, tradeAmt, ActivityEnum.ActivityPlatformType.OnLine, CommonEnum.GoodType.Goods));
		return Response.getSuccess(data);
	}

	@Override
	public Response availableBenefitByServiceMall(Long memberId, Long goodsId, Integer tradeAmt) throws ParseException {
		// Member member = memberMapper.selectByPrimaryKey(memberId);
		Map<String, Object> data = new HashMap<>();

		// 优惠券
		data.put("can_use_couponList",
				couponUserService.listUserCouponsInfo(memberId, goodsId, tradeAmt, ActivityEnum.ActivityPlatformType.OnLine, CommonEnum.GoodType.Service));
		return Response.getSuccess(data);
	}


    @Override
    public Response availableBenefitCart(Long memberId, List<Long> goodIds) throws ParseException {
        Member member = memberMapper.selectByPrimaryKey(memberId);
		MemberGrade memberGrade = memberGradeMapper.queryMemberGrade(member.getGradeId());
//        BonusVerifyRule bonusVerifyRule = bonusVerifyRuleMapper.getDefaultByGroupId(member.getGroupId());
        List<MallCart> mallCartList = mallCartMapper.listByMemberIdAndCartId(memberId, goodIds);

		//带金额的 求交 后去重
        Map<String, Object> data = new HashMap<>();
        List<Map<String, Object>> canUseCouponList = new ArrayList<>();
        int maxCanUseBonus = 0;
		BonusVerifyRule bonusVerifyRule=null;
        for(MallCart mallCart : mallCartList) {
			MallEntityGood mallEntityGood = null;
			if(mallCart.getSpecId() == null) {
				mallEntityGood = mallEntityGoodMapper.selectByPrimaryKey(mallCart.getGoodId());
			} else {
				mallEntityGood = mallEntityGoodMapper.selectBySpecId(mallCart.getSpecId());
			}
			logger.debug(">>>>第一次<<<<<<");
			logger.debug(">>>>一"+mallEntityGood.getShopId()+"<<<<<<");
			logger.debug(">>>>二"+mallEntityGood.getGroupId()+"<<<<<<");
            if(mallEntityGood.getShopId() !=null && mallEntityGood.getGroupId()!=null ){
				logger.debug(">>>一门店<<<<<<");
                bonusVerifyRule = bonusVerifyRuleMapper.qyeryShopVerifyRule(mallEntityGood.getShopId());
            }
            if(bonusVerifyRule ==null){
                //核销规则走渠道的自营
				logger.debug(">>>二渠道<<<<<<");
                bonusVerifyRule = bonusVerifyRuleMapper.getDefaultByGroupId(member.getGroupId());
            }

			int price;
			if(memberGrade.getName().equals(BizEnum.MemberGradeDefault.attention.getName())) {
				price = mallEntityGood.getPromotionPrice2();
			} else {
				price = mallEntityGood.getPromotionPrice();
			}

            int payMethod = mallEntityGood.getPayMethod();
            if(payMethod == BizEnum.MallGoodUseScoreMethod.fixed.getType()) {
                maxCanUseBonus += bonusVerifyRule.getVerifyRate() * mallEntityGood.getMaxPoints() * mallCart.getGoodNumber()/100;
            } else if(payMethod == BizEnum.MallGoodUseScoreMethod.percentage.getType()) {
                maxCanUseBonus += new BigDecimal(mallEntityGood.getMaxPoints()).divide(new BigDecimal(10000),4,BigDecimal.ROUND_FLOOR)
                        .multiply(new BigDecimal(price).divide(new BigDecimal(100), 2 ,BigDecimal.ROUND_FLOOR))
                        .multiply(new BigDecimal(bonusVerifyRule.getVerifyRate())).multiply(new BigDecimal(mallCart.getGoodNumber())).intValue();
            }

            canUseCouponList.addAll(couponUserService.listUserCouponsInfo(memberId, mallCart.getGoodId(), price * mallCart.getGoodNumber(),
                    ActivityEnum.ActivityPlatformType.OnLine, CommonEnum.GoodType.Goods));
        }

		//不带金额的
		List<Map<String, Object>> canUseCouponList2 = new ArrayList<>();
		int maxCanUseBonus2 = 0;
		for(MallCart mallCart : mallCartList) {
			MallEntityGood mallEntityGood = null;
			if(mallCart.getSpecId() == null) {
				mallEntityGood = mallEntityGoodMapper.selectByPrimaryKey(mallCart.getGoodId());
			} else {
				mallEntityGood = mallEntityGoodMapper.selectBySpecId(mallCart.getSpecId());
			}

			logger.debug(">>>>第二次<<<<<<");
			logger.debug(">>>>二"+mallEntityGood.getShopId()+"<<<<<<");
			logger.debug(">>>>二"+mallEntityGood.getGroupId()+"<<<<<<");


			if(mallEntityGood.getShopId() !=null && mallEntityGood.getGroupId()!=null ){
				logger.debug(">>>二门店<<<<<<");
				bonusVerifyRule = bonusVerifyRuleMapper.qyeryShopVerifyRule(mallEntityGood.getShopId());
			}
			if(bonusVerifyRule==null){
				//核销规则走渠道的自营
				logger.debug(">>>二渠道<<<<<<");
				bonusVerifyRule = bonusVerifyRuleMapper.getDefaultByGroupId(member.getGroupId());
			}


			int price;
			if(memberGrade.getName().equals(BizEnum.MemberGradeDefault.attention.getName())) {
				price = mallEntityGood.getPromotionPrice2();
			} else {
				price = mallEntityGood.getPromotionPrice();
			}

			int payMethod = mallEntityGood.getPayMethod();
			if(payMethod == BizEnum.MallGoodUseScoreMethod.fixed.getType()) {
				maxCanUseBonus2 += bonusVerifyRule.getVerifyRate() * mallEntityGood.getMaxPoints() * mallCart.getGoodNumber()/100;
			} else if(payMethod == BizEnum.MallGoodUseScoreMethod.percentage.getType()) {
				maxCanUseBonus2 += new BigDecimal(mallEntityGood.getMaxPoints()).divide(new BigDecimal(10000),4,BigDecimal.ROUND_FLOOR)
						.multiply(new BigDecimal(price).divide(new BigDecimal(100), 2 ,BigDecimal.ROUND_FLOOR))
						.multiply(new BigDecimal(bonusVerifyRule.getVerifyRate())).multiply(new BigDecimal(mallCart.getGoodNumber())).intValue();
			}

			canUseCouponList2.addAll(couponUserService.listUserCouponsInfo(memberId, mallCart.getGoodId(), null,
					ActivityEnum.ActivityPlatformType.OnLine, CommonEnum.GoodType.Goods));
		}
		//去重
		for (int i = 0; i < canUseCouponList2.size() - 1; i++) {
			for (int j = canUseCouponList2.size() - 1; j > i; j--) {
				if (canUseCouponList2.get(j).get("id").equals(canUseCouponList2.get(i).get("id"))) {
					canUseCouponList2.remove(j);
				}
			}
		}

		//两个大list 合并 在去重得到所有满足的条件

		canUseCouponList.addAll(canUseCouponList2);
		for (int i = 0; i < canUseCouponList.size() - 1; i++) {
			for (int j = canUseCouponList.size() - 1; j > i; j--) {
				if (canUseCouponList.get(j).get("id").equals(canUseCouponList.get(i).get("id"))) {
					canUseCouponList.remove(j);
				}
			}
		}

		System.out.print(canUseCouponList);
		System.out.print("结束_________________________________________________________");
		System.out.print("--------------------------"+canUseCouponList.size()+"-------------------------");


        data.put("user_bonus_amount", member.getBonusAmount());
        data.put("bonus_verify_rate", bonusVerifyRule.getVerifyRate());
        data.put("maxCanUseBonus", maxCanUseBonus);
		data.put("memberDiscount", memberGrade.getDiscountRate());

		Set<String> couponSns = new HashSet<>();
        Iterator<Map<String, Object>> couponIterator = canUseCouponList.iterator();
        while(couponIterator.hasNext()) {
            Map<String, Object> coupon = couponIterator.next();
            if(!couponSns.add((String)coupon.get("sn"))) {
                couponIterator.remove();
            }
        }

        data.put("can_use_couponList", canUseCouponList);
        return Response.getSuccess(data);
    }

	/**
	 * 购物车订单提交
	 * @param memberId
	 * @param goodIds
	 * @param addressId
	 * @param bonus
	 * @param couponSns
	 * @return
	 * @throws ApplicationException
	 */
	/*@Override
    public Response saveSubmitCartOrder(Long memberId, ArrayList<Long> goodIds, Long addressId, Integer bonus, String couponSns)
            throws ApplicationException {
		Date date = new Date();

		Member member = memberMapper.selectByPrimaryKey(memberId);//查询会员信息
		MemberGrade memberGrade = memberGradeMapper.queryMemberGrade(member.getGradeId());//查询会员等级信息
		BonusVerifyRule bonusVerifyRule = bonusVerifyRuleMapper.getDefaultByGroupId(member.getGroupId());//查询积分核销信息

		List<MallCart> mallCartList = mallCartMapper.listByMemberIdAndCartId(memberId, goodIds);//查询会员的购物车信息

		Integer memberDiscount = (Integer) wxApiMemberService.findMemberDisCount(memberId.toString()).get("member_disCount");//查询该会员的会员折扣率

		MemberAddress memberAddress = memberAddressMapper.selectByMemberIdAndId(memberId, addressId);//查询会员收货地址信息
		String memberProvence = memberAddress.getCity().split(" ")[0].substring(0, 2);
		int memberProvenceId = citiesMapper.selectByName(memberProvence);

		List allData = new ArrayList();


		Map<String, MallEntityGood> mallEntityGoodMap = new HashMap<>();
		Map<String, Object> allOrderCount = new HashMap<>();//所有子订单的总计
		boolean couponCanUse = false;//能否使用优惠券

		Long shopid = 0L;//门店ID


		//所有订单综合
		int allFreightAmount = 0;//所有结算订单的总运费
		int allGoodTotalNum = 0;//所有结算订单的总数量
		int allGoodTotalAmount = 0;//所有结算订单的商品总价
		int allBonusCoveredMoney = 0;//所有结算订单的积分抵扣金额
		int allCouponCoveredMoney = 0;//所有结算订单的优惠券抵扣金额
		int allPayAmount = 0;//所有结算订单的总价

		Integer freeAmount = 0;

		for (int i = 0; i < mallCartList.size(); i++) {
			MallEntityGood mallEntityGood;

			Map<String, Object> data = new HashMap<>();//回参定义

			int maxCanUseBonus = 0;//最大可用积分
			int couponCoveredMoney = 0;//优惠券抵扣金额
			int bonusCoveredMoney = 0;//积分抵扣金额
			int freightAmount = 0;//总运费
			int goodTotalAmount = 0;//商品总价
			int goodTotalNum = 0;//总商品数量

			String couponSn = null;
			if (couponSns != null && !couponSns.trim().equals("")) {
				couponSn = couponSns.split(",")[0];//只能选择一个优惠券
			}

			String orderNo = Const.CONSUMPTION_REAL + UtilFun.createOrderNum();//生成订单编号
			data.put("orderNum", orderNo);

			//商品有规格价，就使用规格价；没有规格价，就使用原始价格
			if (mallCartList.get(i).getSpecId() == null) {
				mallEntityGood = mallEntityGoodMapper.selectByPrimaryKey(mallCartList.get(i).getGoodId());
			} else {
				mallEntityGood = mallEntityGoodMapper.selectBySpecId(mallCartList.get(i).getSpecId());
			}

			//如果是会员，就用会员价；不是会员就用现价
			int price;
			if (memberGrade.getName().equals(BizEnum.MemberGradeDefault.attention.getName())) {
				price = mallEntityGood.getPromotionPrice2();
			} else {
				price = mallEntityGood.getPromotionPrice();
			}

			//门店ID
			shopid = mallEntityGood.getShopId();
			mallEntityGoodMap.put(mallEntityGood.getId().toString(), mallEntityGood);

			//总金额和总数量
			goodTotalNum += mallCartList.get(i).getGoodNumber();
			goodTotalAmount += mallCartList.get(i).getGoodNumber() * price;

			//优惠券是否可用
			if (couponSn != null) {
				CouponUser couponUser = couponUserMapper.getCanUseCouponBySnAndGoodId(couponSn, date, memberId, mallEntityGood.getId());
				if (couponUser != null) {
					couponCanUse = true;
					couponCoveredMoney = couponUser.getFaceValue();
				}
			}

			//所有最大可用积分计算
			if (bonus > 0) {
				int payMethod = mallEntityGood.getPayMethod();
				if (payMethod == BizEnum.MallGoodUseScoreMethod.fixed.getType()) {
					maxCanUseBonus += bonusVerifyRule.getVerifyRate() * mallEntityGood.getMaxPoints() * mallCartList.get(i).getGoodNumber() / 100;
				} else if (payMethod == BizEnum.MallGoodUseScoreMethod.percentage.getType()) {
					maxCanUseBonus += new BigDecimal(mallEntityGood.getMaxPoints()).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_FLOOR)
							.multiply(new BigDecimal(price)).multiply(new BigDecimal(bonusVerifyRule.getVerifyRate())).intValue()
							* mallCartList.get(i).getGoodNumber();
				}
			}

			MallFreightDetail mallFreightDetail = mallFreightDetailMapper.selectByFreightIdAndProvenceId(mallEntityGood.getPostMethod(), memberProvenceId);
			MallFreight mallFreight = mallFreightMapper.selectByPrimaryKey(mallEntityGood.getPostMethod());
			if (mallFreightDetail != null && mallFreightDetail.getFreeAmount() != null && mallFreightDetail.getFreeAmount() > freeAmount) {
				freeAmount = mallFreightDetail.getFreeAmount();
			}

			freightAmount += calFreight(mallEntityGood, mallCartList.get(i).getGoodNumber(), mallFreightDetail, memberAddress, mallFreight, memberProvenceId);
			allFreightAmount += freightAmount;

			if (freeAmount != 0 && freeAmount < goodTotalAmount) {
				freightAmount = 0;
			}

			if (goodTotalNum == 0) {
				return Response.getError("请不要重复提交订单");
			}

			if (couponSn != null && !couponCanUse) {
				return Response.getError("非法请求");
			}

			if (maxCanUseBonus < bonus || member.getBonusAmount() < bonus) {
				return Response.getError("非法请求");
			}

			if (bonus > 0) {
				bonusCoveredMoney = new BigDecimal(bonus).divide(new BigDecimal(bonusVerifyRule.getVerifyRate()), 2, BigDecimal.ROUND_FLOOR)
						.multiply(new BigDecimal(100)).intValue();
			}

			data.put("bonusCoveredMoney", bonusCoveredMoney);
			data.put("couponCoveredMoney", couponCoveredMoney);


			goodTotalAmount = goodTotalAmount * memberDiscount / 100;

			allBonusCoveredMoney += bonusCoveredMoney;
			allCouponCoveredMoney += couponCoveredMoney;
			allGoodTotalAmount += goodTotalAmount;

			//订单创建
			OrderGood orderGood = new OrderGood();
			orderGood.setShopId(shopid);
			orderGood.setOrderNo(orderNo);
			orderGood.setGmtModified(date);
			orderGood.setGmtCreate(date);
			orderGood.setMemberId(memberId);
			orderGood.setGoodNum(goodTotalNum);
			orderGood.setGoodAmount(goodTotalAmount);
			orderGood.setBonusCover(bonusCoveredMoney);
			orderGood.setBonusAmount(bonus);
			orderGood.setFreightCharge(freightAmount);
			orderGood.setCouponCover(couponCoveredMoney);
			orderGood.setMemberDiscount(memberDiscount);
			orderGood.setStatus(BizEnum.MallOrderStatus.WaitingForPay.getType());
			orderGood.setAddressId(addressId);
			orderGood.setGroupId(member.getGroupId());

			int j = orderGoodMapper.insertSelective(orderGood);


			long goodId = mallCartList.get(i).getGoodId();
			int goodsNum = mallCartList.get(i).getGoodNumber();
			MallEntityGood mallEntityGood2 = mallEntityGoodMap.get(goodId + "");
			//减库存
			try {
				mallEntityGoodMapper.reduceGoodStockNumber(goodId, goodsNum);
				if (mallCartList.get(i).getSpecId() != null) {
					mallEntityGoodSpecMapper.reduceGoodStockNumber(mallCartList.get(i).getSpecId(), goodsNum);
				}
				mallEntityGoodMapper.updateUnlaunchGood(goodId);
			} catch (Exception ae) {
				ae.printStackTrace();
				throw new ApplicationException("商品 " + mallEntityGood2.getName() + " 库存不足");
			}

			OrderGoodItem orderGoodItem = new OrderGoodItem();
			orderGoodItem.setShareMemberId(mallCartList.get(i).getShareMemberId());
			orderGoodItem.setGoodId(goodId);
			orderGoodItem.setGoodNum(goodsNum);
			if (mallCartList.get(i).getSpecId() != null) {
				orderGoodItem.setGoodSpecId(mallCartList.get(i).getSpecId());
			}
			orderGoodItem.setGoodName(mallEntityGood2.getName());
			orderGoodItem.setGoodsImage(mallEntityGood2.getPicture().split(",")[0]);
			orderGoodItem.setOrderId(orderGood.getId());
			orderGoodItem.setOriginalPrice(mallEntityGood2.getSalePrice());
			orderGoodItem.setPromotionPrice(memberGrade.getName().equals(BizEnum.MemberGradeDefault.attention.getName()) ?
					mallEntityGood2.getPromotionPrice2() : mallEntityGood2.getPromotionPrice());
			orderGoodItem.setSettingPrice(mallEntityGood2.getSupplyPrice());
			orderGoodItem.setShopId(mallEntityGood2.getShopId());
			orderGoodItem.setIsSetted(false);
			orderGoodItemMapper.insertSelective(orderGoodItem);


			//积分锁定
			if (bonus > 0) {
				try {
					memberMapper.updateMemberBonusLock(memberId, bonus);
				} catch (Exception e) {
					e.printStackTrace();
					throw new ApplicationException("用户积分核销失败");
				}

				BonusVerifyLog bonusVerifyLog = new BonusVerifyLog();
				bonusVerifyLog.setAdjustAmount(bonus);
				bonusVerifyLog.setAdjustStatus(ActivityEnum.BonusVerityStatus.Locked.getType());
				bonusVerifyLog.setAdjustValue(bonusCoveredMoney);
				bonusVerifyLog.setMemberId(memberId);
				bonusVerifyLog.setGmtCreate(date);
				bonusVerifyLog.setGmtModified(date);
				bonusVerifyLog.setOrderId(orderGood.getId());
				bonusVerifyLog.setGroupId(member.getGroupId());
				bonusVerifyLog.setVerifyType(ActivityEnum.BonusVerityType.Consume.getType());
				bonusVerifyLogMapper.insertSelective(bonusVerifyLog);
			}

			//优惠券锁定
			if (couponSn != null) {
				int z = couponUserMapper.updateLockCoupons(memberId, null, date, orderGood.getId(), couponSn);
				if (z != 1) {
					throw new ApplicationException("订单创建失败");
				}
			}

			//删除购物车商品
			mallCartMapper.deleteByIdsAndMemberId(member.getId(), goodIds);
			data.put("payAmount", goodTotalAmount + freightAmount - couponCoveredMoney - bonusCoveredMoney);
			allData.add(i, data);
		}
		allPayAmount = allGoodTotalAmount + allFreightAmount - allCouponCoveredMoney - allBonusCoveredMoney;
		allOrderCount.put("allBonusCoveredMoney", allBonusCoveredMoney);
		allOrderCount.put("allCouponCoveredMoney", allCouponCoveredMoney);
		allOrderCount.put("allPayAmount", allPayAmount);

		allData.add(0, allOrderCount);

		Response.buildSuccess(allData, "成功");
		return Response.buildSuccess(allData, "订单创建成功");
    }*/

   @Override
    public Response saveSubmitCartOrder(Long memberId, ArrayList<Long> goodIds, Long addressId, Integer bonus, String couponSns)
            throws ApplicationException {
        Date date = new Date();
        String orderNo = Const.CONSUMPTION_REAL + UtilFun.createOrderNum();
        Map<String, Object> data = new HashMap<>();
        data.put("orderNum", orderNo);

        String couponSn = null;
        if(couponSns != null && !couponSns.trim().equals("")) {
            couponSn = couponSns.split(",")[0];    //只能选择一个优惠券
        }

        Member member = memberMapper.selectByPrimaryKey(memberId);
		MemberGrade memberGrade = memberGradeMapper.queryMemberGrade(member.getGradeId());

	    List<MallCart> mallCartList = mallCartMapper.listByMemberIdAndCartId(memberId, goodIds);
//	    BonusVerifyRule bonusVerifyRule = bonusVerifyRuleMapper.getDefaultByGroupId(member.getGroupId());

		Integer memberDiscount = (Integer) wxApiMemberService.findMemberDisCount(memberId.toString()).get("member_disCount");

		MemberAddress memberAddress = memberAddressMapper.selectByMemberIdAndId(memberId, addressId);
		String memberProvence = memberAddress.getCity().split(" ")[0].substring(0, 2);
		int memberProvenceId = citiesMapper.selectByName(memberProvence);

        Map<String, MallEntityGood> mallEntityGoodMap = new HashMap<>();

        boolean couponCanUse = false;
        int maxCanUseBonus = 0;
        int couponCoveredMoney = 0;
        int bonusCoveredMoney = 0;
        int freightAmount = 0;
        Long goodTotalAmount = 0l;
        int goodTotalNum = 0;
        Long shopid = 0L;

        Integer freeAmount = 0;

	   BonusVerifyRule bonusVerifyRule=null;

        for(MallCart mallCart : mallCartList) {
			MallEntityGood mallEntityGood;
        	if(mallCart.getSpecId() == null) {
				mallEntityGood = mallEntityGoodMapper.selectByPrimaryKey(mallCart.getGoodId());
			} else {
        		mallEntityGood = mallEntityGoodMapper.selectBySpecId(mallCart.getSpecId());
			}
			//门店核销规则
			if(mallEntityGood.getShopId() !=null && mallEntityGood.getGroupId()!=null ){
				bonusVerifyRule = bonusVerifyRuleMapper.qyeryShopVerifyRule(mallEntityGood.getShopId());
			}
			if(bonusVerifyRule ==null){
				//核销规则走渠道的自营
				bonusVerifyRule = bonusVerifyRuleMapper.getDefaultByGroupId(member.getGroupId());
			}

			int price;
			if(memberGrade.getName().equals(BizEnum.MemberGradeDefault.attention.getName())) {
				price = mallEntityGood.getPromotionPrice2();
			} else {
				price = mallEntityGood.getPromotionPrice();
			}

			shopid = mallEntityGood.getShopId();
            mallEntityGoodMap.put(mallEntityGood.getId().toString(), mallEntityGood);

            //总金额和总数量
            goodTotalNum += mallCart.getGoodNumber();
            goodTotalAmount += mallCart.getGoodNumber() * price;

            logger.info("goodTotalAmount=============="+goodTotalAmount);
            logger.info("goodTotalNum=============="+goodTotalNum);

            //优惠券是否可用
            if(couponSn != null) {
                CouponUser couponUser = couponUserMapper.getCanUseCouponBySnAndGoodId(couponSn, date, memberId, mallEntityGood.getId());
                if(couponUser != null) {
                    couponCanUse = true;
                    couponCoveredMoney = couponUser.getFaceValue();
                }
            }

            //所有最大可用积分计算
            if(bonus > 0) {
                int payMethod = mallEntityGood.getPayMethod();
                if(payMethod == BizEnum.MallGoodUseScoreMethod.fixed.getType()) {
                    maxCanUseBonus += bonusVerifyRule.getVerifyRate() * mallEntityGood.getMaxPoints() * mallCart.getGoodNumber()/100;
                } else if(payMethod == BizEnum.MallGoodUseScoreMethod.percentage.getType()) {
                    maxCanUseBonus += new BigDecimal(mallEntityGood.getMaxPoints()).divide(new BigDecimal(10000),4,BigDecimal.ROUND_FLOOR)
                            .multiply(new BigDecimal(price)).multiply(new BigDecimal(bonusVerifyRule.getVerifyRate())).intValue()
                            * mallCart.getGoodNumber();
                }
            }

            //运费计算
//            if(freightAmount > 0) {
//                int goodFreight = calFreight(memberId, addressId, mallEntityGood.getId(), mallCart.getGoodNumber());
//                if(goodFreight != 0) {
//                    freightAmount += goodFreight;
//                } else {
//                    freightAmount = 0;
//                }
//            }

			MallFreightDetail mallFreightDetail = mallFreightDetailMapper.selectByFreightIdAndProvenceId(mallEntityGood.getPostMethod(), memberProvenceId);
			MallFreight mallFreight = mallFreightMapper.selectByPrimaryKey(mallEntityGood.getPostMethod());
            if(mallFreightDetail != null&&mallFreightDetail.getFreeAmount()!=null&&mallFreightDetail.getFreeAmount() > freeAmount) {
				freeAmount = mallFreightDetail.getFreeAmount();
            }

			freightAmount += calFreight(mallEntityGood, mallCart.getGoodNumber(), mallFreightDetail, memberAddress, mallFreight, memberProvenceId);
        }

        if(freeAmount != 0 && freeAmount < goodTotalAmount) {
        	freightAmount = 0;
		}

        if(goodTotalNum == 0) {
            return Response.getError("请不要重复提交订单");
        }

        if(couponSn != null && !couponCanUse) {
            return Response.getError("非法请求");
        }

        if(maxCanUseBonus < bonus || member.getBonusAmount() < bonus) {
            return Response.getError("非法请求");
        }

        if(bonus > 0) {
            bonusCoveredMoney = new BigDecimal(bonus).divide(new BigDecimal(bonusVerifyRule.getVerifyRate()),2, BigDecimal.ROUND_FLOOR)
                    .multiply(new BigDecimal(100)).intValue();
        }

        data.put("bonusCoveredMoney", bonusCoveredMoney);
        data.put("couponCoveredMoney", couponCoveredMoney);

        logger.info("========goodTotalAmount=========="+goodTotalAmount);
        logger.info("========memberDiscount=========="+memberDiscount);

        float dis = Float.parseFloat(memberDiscount.toString()) / 100;
        float amount = Float.parseFloat(goodTotalAmount.toString()) * dis;
        goodTotalAmount=(long)amount;
//       goodTotalAmount = goodTotalAmount * memberDiscount / 100;

		logger.info("========goodTotalAmount=========="+goodTotalAmount);

        //订单创建
        OrderGood orderGood = new OrderGood();
        orderGood.setShopId(shopid);
        orderGood.setOrderNo(orderNo);
        orderGood.setGmtModified(date);
        orderGood.setGmtCreate(date);
        orderGood.setMemberId(memberId);
        orderGood.setGoodNum(goodTotalNum);
        orderGood.setGoodAmount(Integer.parseInt(goodTotalAmount.toString()));
        orderGood.setBonusCover(bonusCoveredMoney);
        orderGood.setBonusAmount(bonus);
        orderGood.setFreightCharge(freightAmount);
        orderGood.setCouponCover(couponCoveredMoney);
        orderGood.setMemberDiscount(memberDiscount);
        orderGood.setStatus(BizEnum.MallOrderStatus.WaitingForPay.getType());
        orderGood.setAddressId(addressId);
        orderGood.setGroupId(member.getGroupId());

        int j = orderGoodMapper.insertSelective(orderGood);

        Long sid=null;

    	if(j == 1) {
            for(MallCart mallCart : mallCartList) {
                long goodId = mallCart.getGoodId();
                int goodsNum = mallCart.getGoodNumber();
                MallEntityGood mallEntityGood = mallEntityGoodMap.get(goodId+"");
                //减库存
                try {
                    mallEntityGoodMapper.reduceGoodStockNumber(goodId, goodsNum);
                    if(mallCart.getSpecId() != null) {
                    	mallEntityGoodSpecMapper.reduceGoodStockNumber(mallCart.getSpecId(), goodsNum);
					}
                    mallEntityGoodMapper.updateUnlaunchGood(goodId);
                } catch (Exception ae) {
                    ae.printStackTrace();
                    throw new ApplicationException("商品 " + mallEntityGood.getName() + " 库存不足");
                }
                if(mallEntityGood.getShopId() !=null){
					sid=mallEntityGood.getShopId();
				}

                OrderGoodItem orderGoodItem = new OrderGoodItem();
                orderGoodItem.setShareMemberId(mallCart.getShareMemberId());
                orderGoodItem.setGoodId(goodId);
                orderGoodItem.setGoodNum(goodsNum);
                if(mallCart.getSpecId() != null) {
                	orderGoodItem.setGoodSpecId(mallCart.getSpecId());
				}
                orderGoodItem.setGoodName(mallEntityGood.getName());
                orderGoodItem.setGoodsImage(mallEntityGood.getPicture().split(",")[0]);
                orderGoodItem.setOrderId(orderGood.getId());
                orderGoodItem.setOriginalPrice(mallEntityGood.getSalePrice());
                orderGoodItem.setPromotionPrice(memberGrade.getName().equals(BizEnum.MemberGradeDefault.attention.getName()) ?
						mallEntityGood.getPromotionPrice2() : mallEntityGood.getPromotionPrice());

                int settingPrice =mallEntityGood.getSupplyPrice()+freightAmount;
				settingPrice=  Integer.parseInt(String.valueOf(Math.round(settingPrice * (1 - 0.006))));
                orderGoodItem.setSettingPrice(settingPrice);


//                orderGoodItem.setSettingPrice(mallEntityGood.getSupplyPrice());
    	        orderGoodItem.setShopId(mallEntityGood.getShopId());
    	        orderGoodItem.setIsSetted(false);
                orderGoodItemMapper.insertSelective(orderGoodItem);
            }

            //积分锁定
            if(bonus > 0) {
                try {
                    memberMapper.updateMemberBonusLock(memberId, bonus);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new ApplicationException("用户积分核销失败");
                }

                BonusVerifyLog bonusVerifyLog = new BonusVerifyLog();
                bonusVerifyLog.setAdjustAmount(bonus);
                bonusVerifyLog.setAdjustStatus(ActivityEnum.BonusVerityStatus.Locked.getType());
                bonusVerifyLog.setAdjustValue(bonusCoveredMoney);
                bonusVerifyLog.setMemberId(memberId);
                bonusVerifyLog.setGmtCreate(date);
                bonusVerifyLog.setGmtModified(date);
                bonusVerifyLog.setOrderId(orderGood.getId());
                bonusVerifyLog.setGroupId(member.getGroupId());
                bonusVerifyLog.setShopId(sid);
                bonusVerifyLog.setVerifyType(ActivityEnum.BonusVerityType.Consume.getType());
                bonusVerifyLogMapper.insertSelective(bonusVerifyLog);
            }

            //优惠券锁定
            if(couponSn != null) {
                int z = couponUserMapper.updateLockCoupons(memberId, null, date, orderGood.getId(), couponSn);
                if(z != 1) {
                    throw new ApplicationException("订单创建失败");
                }
            }

            //删除购物车商品
            mallCartMapper.deleteByIdsAndMemberId(member.getId(), goodIds);

            data.put("payAmount", goodTotalAmount + freightAmount - couponCoveredMoney - bonusCoveredMoney);
            return Response.buildSuccess(data, "订单创建成功");
        }
        throw new ApplicationException("订单创建失败");
    }

	@Override
	public Response saveSubmitOrder(Long memberId, Long goodId, Integer goodsNum, Long addressId, Integer bonus,
									String couponSns,Long specId, Long sharememberid) throws ApplicationException {
   		logger.info("::::::::::::::::::::::::::::::::"+specId);
		Date date = new Date();
		String orderNo = Const.CONSUMPTION_REAL + UtilFun.createOrderNum();
		Map<String, Object> data = new HashMap<>();
		data.put("orderNum", orderNo);

		Member member = memberMapper.selectByPrimaryKey(memberId);
		if (bonus != null && bonus > member.getBonusAmount()) {
			return null;
		}

		Integer memberDiscount = (Integer) wxApiMemberService.findMemberDisCount(memberId.toString()).get("member_disCount");
//  	根据等级来确定显示会员价还是非会员价
// 		MemberGrade memberGrade = memberGradeMapper.queryMemberGrade(member.getGradeId());
		//根据会员是否开通钱包


		MallEntityGood mallEntityGood = mallEntityGoodMapper.selectByPrimaryKey(goodId);

		BonusVerifyRule bonusVerifyRule=null;
		//积分核销比例  自营商品走渠道的核销比例 门店商品走门店的核销比例
		if(mallEntityGood.getGroupId()!=null && mallEntityGood.getShopId() !=null){
			//门店
			 bonusVerifyRule = bonusVerifyRuleMapper.qyeryShopVerifyRule(mallEntityGood.getShopId());
		}
		if(bonusVerifyRule==null){
			//自营
			 bonusVerifyRule = bonusVerifyRuleMapper.getDefaultByGroupId(member.getGroupId());
		}


		if (mallEntityGood.getLimitNumber() > 0) {
			long memberHavePurchaseNum = orderGoodItemMapper.countMemberHavePurchase(memberId, mallEntityGood.getId());
			if (memberHavePurchaseNum + goodsNum > mallEntityGood.getLimitNumber()) {
				return Response.getError("商品 " + mallEntityGood.getName() + " 超过最大购买数量，请重新选择");
			}
		}
		if(mallEntityGood.getIsLaunch() == null || mallEntityGood.getIsLaunch() == 0) {
			return Response.getError("商品 " + mallEntityGood.getName() + " 已下架，请选择其他商品");
		}

		MallEntityGoodSpec mallEntityGoodSpec = null;
		Long totalAmount = 0l;
		int price;
		if(specId != null) {
			mallEntityGoodSpec = mallEntityGoodSpecMapper.selectByPrimaryKey(specId);

//			if(memberGrade.getName().equals(BizEnum.MemberGradeDefault.attention.getName())) {
			if(member.getWalletStatus()==0) {
				price = mallEntityGoodSpec.getPrice2();
			} else {
				price = mallEntityGoodSpec.getPrice();
			}

			totalAmount = price * goodsNum.longValue();
		} else {

//			if(memberGrade.getName().equals(BizEnum.MemberGradeDefault.attention.getName())) {
			if(member.getWalletStatus()==0) {
					price = mallEntityGood.getPromotionPrice2();
			} else {
				price = mallEntityGood.getPromotionPrice();
			}

//			totalAmount = price * goodsNum;
            totalAmount = price * goodsNum.longValue();
		}

        float dis = Float.parseFloat(memberDiscount.toString()) / 100;
        float amount = Float.parseFloat(totalAmount.toString()) * dis;
        totalAmount=(long)amount;
//		totalAmount = totalAmount * memberDiscount / 100;

		int payMethod = mallEntityGood.getPayMethod();

		int maxCanUseBonus = 0;
		if (payMethod == BizEnum.MallGoodUseScoreMethod.fixed.getType()) {
			/*if(mallEntityGood.getMaxPoints()>totalAmount){
				maxCanUseBonus=totalAmount;
			}else{
				maxCanUseBonus = bonusVerifyRule.getVerifyRate() * mallEntityGood.getMaxPoints() * goodsNum;
			}*/
			maxCanUseBonus = bonusVerifyRule.getVerifyRate() * mallEntityGood.getMaxPoints() * goodsNum;
		} else if (payMethod == BizEnum.MallGoodUseScoreMethod.percentage.getType()) {
			maxCanUseBonus = new BigDecimal(mallEntityGood.getMaxPoints()).divide(new BigDecimal(10000), 4, BigDecimal.ROUND_FLOOR)
					.multiply(new BigDecimal(price).divide(new BigDecimal(100), 2, BigDecimal.ROUND_FLOOR))
					.multiply(new BigDecimal(bonusVerifyRule.getVerifyRate())).multiply(new BigDecimal(goodsNum)).intValue();

			/*if(maxCanUseBonus*10>totalAmount){
				maxCanUseBonus=totalAmount/10;
			}*/
		}
		if (bonus != null && maxCanUseBonus < bonus) {
			return null; // 非法请求
		}

		int bonusCoveredMoney = 0;
		if (bonus != null) {
			bonusCoveredMoney = new BigDecimal(bonus).divide(new BigDecimal(bonusVerifyRule.getVerifyRate()), 2, BigDecimal.ROUND_FLOOR)
					.multiply(new BigDecimal(100)).intValue();
		}

		// 优惠券合法性判断
		String[] couponSnsArray = null;
		Integer couponCoverAmount = 0;
		if (couponSns != null && !Tools.isEmpty(couponSns)) {
			couponSnsArray = couponSns.split(",");
			if (couponSnsArray.length > 1) {
			} else {
				CouponUser couponUser = couponUserMapper.selectByCouponSn(couponSnsArray[0]);
				if (couponUser != null) {
					if (couponUser.getLimitAmount() > totalAmount) {
						return null;
					} else {
						couponCoverAmount = couponUser.getFaceValue();
					}
				}
			}
		}

		MemberAddress memberAddress = memberAddressMapper.selectByMemberIdAndId(memberId, addressId);
		String memberProvence = memberAddress.getCity().split(" ")[0].substring(0, 2);
		int memberProvenceId = citiesMapper.selectByName(memberProvence);


		if(specId == null) {
			mallEntityGood = mallEntityGoodMapper.selectByPrimaryKey(goodId);
		} else {
			mallEntityGood = mallEntityGoodMapper.selectBySpecId(specId);
		}

		int freightAmount = 0;

		//运费计算
		MallFreightDetail mallFreightDetail = mallFreightDetailMapper.selectByFreightIdAndProvenceId(mallEntityGood.getPostMethod(), memberProvenceId);
		MallFreight mallFreight = mallFreightMapper.selectByPrimaryKey(mallEntityGood.getPostMethod());
		if(mallFreightDetail == null) {
			freightAmount = calFreight(mallEntityGood, goodsNum, mallFreightDetail, memberAddress, mallFreight, memberProvenceId);
		} else {
			if(mallFreightDetail.getFreeAmount()!=null){
				if(mallFreightDetail.getFreeAmount() > totalAmount) {//非免运费
					freightAmount = calFreight(mallEntityGood, goodsNum, mallFreightDetail, memberAddress, mallFreight, memberProvenceId);
				}
			}else{
				freightAmount = calFreight(mallEntityGood, goodsNum, mallFreightDetail, memberAddress, mallFreight, memberProvenceId);
				logger.info("+++++++++++++运费+++++++++++"+freightAmount);
				}
		}
		//if(mallFreightDetail == null && mallFreightDetail.getFreeAmount() == null && mallFreightDetail.getFreeAmount() > totalAmount) {// - couponCoverAmount - bonusCoveredMoney

		//}

		//减少库存以及自动下架处理
		try {
			if(specId != null) {
				mallEntityGoodSpecMapper.reduceGoodStockNumber(specId, goodsNum);
			}
			mallEntityGoodMapper.reduceGoodStockNumber(goodId, goodsNum);
			mallEntityGoodMapper.updateUnlaunchGood(goodId);
		} catch (Exception ae) {
			ae.printStackTrace();
			return Response.getError("商品库存不足");
		}

		OrderGood orderGood = new OrderGood();
		orderGood.setShopId(mallEntityGood.getShopId());
		orderGood.setOrderNo(orderNo);
		orderGood.setGmtModified(date);
		orderGood.setGmtCreate(date);
		orderGood.setGroupId(member.getGroupId());
		orderGood.setMemberId(memberId);
		orderGood.setGoodNum(goodsNum);
		orderGood.setGoodAmount(Integer.parseInt(totalAmount.toString()));
		orderGood.setBonusCover(bonusCoveredMoney);
		orderGood.setMemberDiscount(memberDiscount);
		orderGood.setBonusAmount(bonus);
		orderGood.setFreightCharge(freightAmount);
		orderGood.setCouponCover(couponCoverAmount);
		orderGood.setStatus(BizEnum.MallOrderStatus.WaitingForPay.getType());
		orderGood.setAddressId(addressId);
		int j = orderGoodMapper.insertSelective(orderGood);
		if (j == 1) {
			OrderGoodItem orderGoodItem = new OrderGoodItem();
			orderGoodItem.setGoodId(goodId);
			orderGoodItem.setGoodNum(goodsNum);
			if(specId != null) {
				orderGoodItem.setGoodSpecId(specId);
			}
			orderGoodItem.setGoodName(mallEntityGood.getName());
			orderGoodItem.setGoodsImage(mallEntityGood.getPicture().split(",")[0]);
			orderGoodItem.setOrderId(orderGood.getId());
			orderGoodItem.setOriginalPrice(mallEntityGood.getSalePrice());
			orderGoodItem.setPromotionPrice(price);
			orderGoodItem.setShareMemberId(sharememberid);

			//结算金额计算
			int settingPrice = mallEntityGood.getSupplyPrice()+freightAmount;
			settingPrice=  Integer.parseInt(String.valueOf(Math.round(settingPrice * (1 - 0.006))));
			orderGoodItem.setSettingPrice(settingPrice);

//			orderGoodItem.setSettingPrice(mallEntityGood.getSupplyPrice());
	        orderGoodItem.setShopId(mallEntityGood.getShopId());
	        orderGoodItem.setIsSetted(false);
			orderGoodItemMapper.insertSelective(orderGoodItem);
		}

		// 积分锁定
		if (bonus != null && bonus > 0) {
			int x = memberMapper.updateMemberBonusLock(memberId, bonus);
			if (x == 1) {
				BonusVerifyLog bonusVerifyLog = new BonusVerifyLog();
				bonusVerifyLog.setAdjustAmount(bonus);
				bonusVerifyLog.setAdjustStatus(ActivityEnum.BonusVerityStatus.Locked.getType());
				bonusVerifyLog.setAdjustValue(bonusCoveredMoney);
				bonusVerifyLog.setMemberId(memberId);
				bonusVerifyLog.setGmtCreate(date);
				bonusVerifyLog.setGmtModified(date);
				bonusVerifyLog.setOrderId(orderGood.getId());
				bonusVerifyLog.setGroupId(member.getGroupId());
				if(mallEntityGood.getShopId() !=null){
					bonusVerifyLog.setShopId(mallEntityGood.getShopId());
				}
				bonusVerifyLog.setVerifyType(ActivityEnum.BonusVerityType.Consume.getType());
				bonusVerifyLogMapper.insertSelective(bonusVerifyLog);
			} else {
				throw new ApplicationException("订单创建失败");
			}
		}

		// 优惠券锁定
		if (couponSns != null && couponSnsArray != null) {
			for (int p = 0; p < couponSnsArray.length; p++) {
				int z = couponUserMapper.updateLockCoupons(memberId, null, date, orderGood.getId(), couponSnsArray[p]);
				if (z != 1) {
					throw new ApplicationException("订单创建失败");
				}
			}
		}

		data.put("payAmount", totalAmount + freightAmount - couponCoverAmount - bonusCoveredMoney);
		/*if(mallEntityGood.getShopId()!=null) {//如果是商户商品，则进行推送
			//获取商户账号
			Userbase userbase = shopMapper.getUserNameByShopId(mallEntityGood.getShopId());
			//发送未付款推送信息
			Notice notice = new Notice();
			try {
				notice.setNoticetype(0);
				notice.setSender(mallEntityGood.getGroupId());
				notice.setReceiver(userbase.getUsername());
				notice.setNoticetitle("您有一笔未付款订单");
				notice.setNoticetarget("ACCOUNT");
				notice.setNoticebody("您有一笔未付款订单");
				notice.setGroupid(mallEntityGood.getGroupId());
				notice.setNoticestatus(1);
				notice.setIsplay(1);
				notice.setType(1);
				notice.setTvalue(orderGood.getId().toString());
				appNoticeService.sendNoticeToUsers(notice);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}*/
		return Response.buildSuccess(data, "订单创建成功");
	}

	public Map<String, Object> newBenefitCalc(Long shopid,Integer payAmount, Long groupId, Member member, Long tradeOfflineId) {

   		if(shopid !=null && shopid!=0){

		}else{
   			shopid=null;
		}

		//获取大商户下未关注会员等级ID
		Long memberGradeId;
		if(member != null) {
			memberGradeId = member.getGradeId();
		} else {
		//	memberGradeId = memberGradeMapper.selectMemberGradeByGroupIdAndGradeName(groupId, BizEnum.MemberGradeDefault.unattention.getName()).getId();

			List<MemberGrade> memberGradeList=memberGradeMapper.selectGroupList(groupId);
			memberGradeId =memberGradeList.get(1).getId();
		}

		//查询门店活动信息
		List<ActivityUnroutineRule> activityUnroutineRuleList = activityUnroutineRuleMapper.getByTradeAmountAndOnline(payAmount, groupId,memberGradeId);
		logger.debug(">>>>>>活动规则：" + activityUnroutineRuleList);
		Group group= groupMapper.selectByPrimaryKey(groupId);
		String payGroupCode =group .getPayGroupCode();
		HashMap<String, Object> newBenefitInfo=new HashMap<String, Object>();

		int bonusValue = 0;
		for(int z = 0; z <activityUnroutineRuleList.size(); z++) {
			ActivityUnroutineRule activityUnroutineRule = activityUnroutineRuleList.get(z);

			Byte sendType = activityUnroutineRule.getSendType();
			//会员消费返利
			if (sendType == ActivityEnum.ActivitySendType.Cash.getType() && member != null &&
					member.getWalletStatus() != null && member.getWalletStatus()==1) {
				logger.debug("消费返利");
				Integer backAmt = activityUnroutineRule.getFaceValue();

				if (activityUnroutineRule.getBackMoneyMode() == ActivityEnum.BackMoneyMode.Percentage.getType()) {
					backAmt = new BigDecimal(backAmt).divide(new BigDecimal(100), 2, BigDecimal.ROUND_FLOOR).multiply(new BigDecimal(payAmount)).divide(new BigDecimal(100),2,BigDecimal.ROUND_FLOOR).intValue();
				}

				//余额增加操作
				Date date = new Date();
				String OrgOrderNum = UtilFun.createOrderNum();
				TradeOffline tradeOffline = new TradeOffline();
				tradeOffline.setGroupId(groupId);
				tradeOffline.setTransactionType((byte) BizEnum.TransactionType.ConsumptionBackCash.getType());
				tradeOffline.setOrderId(OrgOrderNum);
				tradeOffline.setPayOrderid(OrgOrderNum);
				tradeOffline.setPayerId(member.getGroupId());
				tradeOffline.setPayerName(group.getMerchantName());
				tradeOffline.setPayerType((byte) CommonEnum.UserType.BusinessManager.getType());
				tradeOffline.setReceiverId(member.getId().toString());
				tradeOffline.setReceiverName(member.getName());
				tradeOffline.setReceiverType((byte) CommonEnum.UserType.User.getType());
				tradeOffline.setOrderAmount(backAmt);
				tradeOffline.setRealAmount(backAmt);
				tradeOffline.setDiscountAmount(0);
				tradeOffline.setSubType((byte)BizEnum.PaymentScene.POS.getType());
				tradeOffline.setPayType((byte) BizEnum.PaymentType.Wallet.getType());
				tradeOffline.setGmtCreate(date);
				tradeOffline.setGmtModified(date);
				tradeOffline.setRelatedTradeOfflineId(tradeOfflineId);
				tradeOffline.setRelatedActivityId(activityUnroutineRule.getActivityId());
				tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
				tradeOffline.setMemo("用户消费返现");
				tradeOffline.setIsWallet(true);


//				PayBalanceChange payBalanceChange = PayBalanceChange.initialize(payGroupCode, member.getVirtualCard(), backAmt.toString(), "0", OrgOrderNum, DateUtils.getDateTimeString("yyyyMMddHHmmss"), UtilFun.createRandomNum(10), "156");
				try {
//					int i = posApiServiceTransactional.saveRebackMoney(tradeOffline, payBalanceChange, tradeOfflineId);
//					newBenefitInfo.put("backAmt", backAmt);
//					logger.debug(">>>>>>返现操作成功，返现金额：" + backAmt);

			            tradeOfflineMapper.insertSelective(tradeOffline);
			            PayResult flag=walletService.updateUserLockedAmount(member.getVirtualCard(), payGroupCode, member.getUserId(), backAmt+"", "0", 0,OrgOrderNum);
			            if(flag==null){
			            	throw new ApplicationException("支付平台余额增加失败");
			            }
			            newBenefitInfo.put("backAmt", backAmt);
						logger.debug(">>>>>>返现操作成功，返现金额：" + backAmt);

					//异步操作扣除营销账户，扣除已使用预算，检查活动是否结束
					new Thread(new AfterRebackMoneyThread(activityUnroutineRule.getActivityId(), backAmt, activityBaseMapper, groupAccountService,null, groupId)).start();
				} catch (ApplicationException e) {
					System.out.println(e.getErrMsg());
					newBenefitInfo.put("backAmt", 0);
				}
				//消费送优惠券
			} else if (sendType == ActivityEnum.ActivitySendType.Coupon.getType()) {
				String[] couponIdsStr = activityUnroutineRule.getCouponId().split(",");
				List<Long> couponIds = new ArrayList<>();
				if(member != null) {
					for (int i = 0; i < couponIdsStr.length; i++) {
						Long couponId = Long.parseLong(couponIdsStr[i]);
						try {
							int x = iCouponUserService.sendOneMemberCoupon(member.getId(), couponId, activityUnroutineRule.getActivityId(), ActivityEnum.RedPackageGetType.ConsumeSend.getType(), tradeOfflineId);
							if(x == 1) {
								couponIds.add(couponId);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				} else {
					for(String couponId : couponIdsStr) {
						couponIds.add(Long.parseLong(couponId));
					}
				}

				if(couponIds.size() > 0) {
					List<Map<String, Object>> couponsInfo = couponMapper.getCouponListById(couponIds);
					List<Map<String, Object>> coupon = new ArrayList<>();
					for (int i = 0; i < couponsInfo.size(); i++) {
						Map<String, Object> coupon1 = new HashMap<>();
						coupon1.put("coupon_id", couponsInfo.get(i).get("id"));
						coupon1.put("coupon_name", couponsInfo.get(i).get("name"));
						coupon1.put("coupon_money", couponsInfo.get(i).get("value"));
						coupon1.put("coupon_type", couponsInfo.get(i).get("couponType"));
						coupon.add(coupon1);
					}
					newBenefitInfo.put("coupon", coupon);
					logger.debug(">>>>>>优惠券：" + coupon);
				}
				//消费送红包
			} else if(sendType == ActivityEnum.ActivitySendType.RedPackage.getType()) {
				Long redpackageId = activityUnroutineRule.getRedpackageId();
				if(member != null) {
					try {
						iRedPackageUserService.sendOneMemberRedPackage(member.getId(), redpackageId, activityUnroutineRule.getActivityId(), ActivityEnum.RedPackageGetType.ConsumeSend.getType(), tradeOfflineId);
					} catch (Exception a) {
						a.printStackTrace();
					}
				} else {
					newBenefitInfo.put("redpackageId", redpackageId);
				}

				//消费送积分
			} else if (sendType == ActivityEnum.ActivitySendType.Bonus.getType() && member != null) {
				int backPoint = activityUnroutineRule.getFaceValue();
				logger.debug("<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>11backPoint：" + backPoint);
				logger.debug("<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>payAmount：" + payAmount);
				if (activityUnroutineRule.getBackMoneyMode() == ActivityEnum.BackMoneyMode.Percentage.getType()) {
					backPoint = new BigDecimal(backPoint).divide(new BigDecimal(100), BigDecimal.ROUND_FLOOR)
							.multiply(new BigDecimal(payAmount)).divide(new BigDecimal(100),BigDecimal.ROUND_FLOOR)
							.divide(new BigDecimal(100), BigDecimal.ROUND_FLOOR).intValue();
					logger.debug("<<<<<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>backPoint：" + backPoint);
				}


				int i = 0;
				if(backPoint >= 1) {
					i = userSendBonus(shopid,groupId, member, backPoint, tradeOfflineId, activityUnroutineRule.getActivityId());
				}

				Integer pointCurrent = member.getBonusAmount();
				Integer realPoint = 0;
				if(i == ActivityEnum.BonusSendStatus.Accounted.getType()) {
					pointCurrent += backPoint;
					realPoint = backPoint;
				} else if(i == ActivityEnum.BonusSendStatus.Accounting.getType()) {
					realPoint = backPoint;
				}
//				BonusVerifyRule bonusVerifyRule=null;
//				if(shopid!=null && member.getGroupId()!=null ){
//					bonusVerifyRule = bonusVerifyRuleMapper.qyeryShopVerifyRule(shopid);
//				}
//				if(bonusVerifyRule ==null){
//					//核销规则走渠道的自营
//					bonusVerifyRule = bonusVerifyRuleMapper.getDefaultByGroupId(member.getGroupId());
//				}

//				if (activityUnroutineRule.getBackMoneyMode() == ActivityEnum.BackMoneyMode.Percentage.getType()) {
//					bonusValue = backPoint / bonusVerifyRule.getVerifyRate();
//				}else{
//					bonusValue = backPoint;
//				}
				bonusValue = backPoint;
				logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>backPoint：" + backPoint);
				logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>bonusValue：" + bonusValue);

				//异步操作扣除营销账户，扣除已使用预算，检查活动是否结束
				if(bonusValue > 0) {
					new Thread(new AfterRebackMoneyThread(activityUnroutineRule.getActivityId(), bonusValue, activityBaseMapper, groupAccountService,backPoint, groupId)).start();
				}

				//积分处理
				newBenefitInfo.put("point", realPoint);
				newBenefitInfo.put("pointCurrent", pointCurrent);
				logger.debug("本次消费获得积分：" + backPoint + " 剩余可用积分：" + pointCurrent);
			}
			activityBaseMapper.addAttendTimes(activityUnroutineRule.getActivityId());
		}

		return newBenefitInfo;
	}

	private int userSendBonus(Long shopid,Long groupId, Member member, Integer backPoint, Long tradeOfflineId, Long activityId) {
		Date date = new Date();
		BonusSendRule bonusSendRule = bonusSendRuleMapper.getDefaultByGroupId(groupId);

		if(bonusSendRule == null) {
			logger.error("未设置默认积分发放风控规则");
			return -1;
		}

		Date hourAndSecond = null;
		try {
			hourAndSecond = DateUtil.cutoutHourAndSecond(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		if(hourAndSecond == null || !bonusCanSend(hourAndSecond, bonusSendRule)) {
			logger.debug("当前时段不发放积分");
			return -1;
		}

		Date dateStart = DateUtil.getDayStart(date);
		Date dateEnd = DateUtil.getAfterDay(dateStart, 1);
		Date bonusSendDate = DateUtil.getAfterHour(date, bonusSendRule.getSendAccountedTime());
		Map<String, Object> userBonusSendRecords = bonusSendLogMapper.getMemberDayBonusSendCount(member.getId(), dateStart, dateEnd);

		BonusSendLog bonusSendLog = new BonusSendLog();
		bonusSendLog.setGroupId(groupId);
		bonusSendLog.setGmtCreate(date);
		bonusSendLog.setGmtModified(date);
		bonusSendLog.setMemberId(member.getId());
		bonusSendLog.setSendType(ActivityEnum.BonusSendType.ConsumeSend.getType());
		bonusSendLog.setAdjustAmount(backPoint);
		bonusSendLog.setOrderId(tradeOfflineId);
//		bonusSendLog.setShopId(-1L);
		bonusSendLog.setShopId(shopid);
		bonusSendLog.setActivityId(activityId);
		bonusSendLog.setAccountingTime(bonusSendDate);

		try {
			posApiServiceTransactional.saveSendBonus(bonusSendLog, member.getId(), backPoint, bonusSendRule, userBonusSendRecords);
		} catch (ApplicationException e) {
			e.printStackTrace();
		}
		return bonusSendLog.getAdjustStatus();
	}

	private boolean bonusCanSend(Date date, BonusSendRule bonusSendRule) {
		return bonusSendRule.getSendTimeType() == ActivityEnum.TimeRangeType.AllDay.getType() ||
				(bonusSendRule.getSendTimeFrom1() != null &&
						bonusSendRule.getSendTimeFrom1().compareTo(date) <= 0 && bonusSendRule.getSendTimeTo1().compareTo(date) >= 0) ||
				(bonusSendRule.getSendTimeFrom2() != null &&
						bonusSendRule.getSendTimeFrom2().compareTo(date) <= 0 && bonusSendRule.getSendTimeTo2().compareTo(date) >= 0) ||
				(bonusSendRule.getSendTimeFrom3() != null &&
						bonusSendRule.getSendTimeFrom3().compareTo(date) <= 0 && bonusSendRule.getSendTimeTo3().compareTo(date) >= 0);
	}

	@Override
	public Response saveWalletPay(Long memberId, String orderId, String payPwd, String payRootHomeURL) throws ApplicationException, ExecutionException, InterruptedException {
		Date date = new Date();

		Member member = memberMapper.checkMemberByIdAndPayPwd(memberId, AES.AESEncode(Const.AceKey, payPwd));
		if (member == null) {
			return Response.getError("支付密码错误");
		}
		logger.info("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^member.getUserId(): "+member.getUserId());

		Group group = groupMapper.selectByPrimaryKey(member.getGroupId());

//		System.out.println(member.getUserId()+"^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
		OrderGood orderGood = orderGoodMapper.selectOrderGoodInfo(orderId, BizEnum.MallOrderStatus.WaitingForPay.getType());
		if (orderGood == null) {
			return Response.getError("订单不存在");
		}
		int realAmount = orderGood.getGoodAmount() + orderGood.getFreightCharge() - orderGood.getBonusCover() - orderGood.getCouponCover();
		realAmount = realAmount >= 0 ? realAmount : 0;


		//钱包支付先去判断钱包余额是否不足
		Boolean flag=memberService.updatequeryMemberBanal(member.getVirtualCard(), group.getPayGroupCode(), member.getUserId(),realAmount);
		if(flag==false){
			return Response.getError("钱包余额不足");
		}


		Long shopid = orderGood.getShopId();
		Shop shop = shopMapper.selectByPrimaryKey(shopid);
		//渠道新增的 自营

		String payOrderId = "MOC" + UtilFun.createRandomNum(10);
		boolean fl = false;
		TradeOffline tradeOffline = tradeOfflineMapper.selectByOrderId(orderId);
		if(tradeOffline == null) {
			fl = true;
			tradeOffline = new TradeOffline();
		}
//		TradeOffline tradeOffline = new TradeOffline();
		tradeOffline.setGroupId(member.getGroupId());
		tradeOffline.setGmtCreate(date);
		tradeOffline.setGmtModified(date);
		tradeOffline.setOrderId(orderId);
		tradeOffline.setRealAmount(realAmount);
		tradeOffline.setOrderAmount(orderGood.getGoodAmount());
		if(shop !=null){
			tradeOffline.setReceiverId(orderGood.getShopId() + "");
			tradeOffline.setReceiverName(shop.getMerchantName());
			tradeOffline.setReceiverType((byte) CommonEnum.UserType.Store.getType());
		}else{
			//自营
			Group group2 = groupMapper.selectByPrimaryKey(orderGood.getGroupId());
			tradeOffline.setReceiverId(orderGood.getGroupId().toString());
			tradeOffline.setReceiverName(group2.getMerchantName());
			tradeOffline.setReceiverType((byte) CommonEnum.UserType.BusinessManager.getType());
		}
		if(orderGood.getCouponCover()<orderGood.getGoodAmount()){
			tradeOffline.setDiscountAmount(orderGood.getCouponCover());
		}else{
			tradeOffline.setDiscountAmount(orderGood.getGoodAmount());
		}
		tradeOffline.setBonusValue(orderGood.getBonusCover());
		tradeOffline.setBonusAmount(orderGood.getBonusAmount());
		tradeOffline.setPayType((byte) BizEnum.PaymentType.Wallet.getType());
		tradeOffline.setSubType((byte) BizEnum.PaymentScene.Online.getType());
		tradeOffline.setPayerId(member.getId());
		tradeOffline.setPayerName(member.getName());
		tradeOffline.setPayerType((byte) CommonEnum.UserType.User.getType());
		tradeOffline.setIsWallet(true);
		tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
		tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
		tradeOffline.setMemo("钱包支付购买实物商品");
		tradeOffline.setPayOrderid(payOrderId);
		int i=0;
		if(fl) {
			 tradeOfflineMapper.insertSelective(tradeOffline);
			 i++;
		} else {

			 tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
			 i++;
		}


//		int i = tradeOfflineMapper.insertSelective(tradeOffline);
		logger.info("==========================保存数据成功==========");
		logger.info("==========================保存数据成功=========="+i);
		if (i == 1) {
			// 更新订单状态
			orderGood.setStatus(BizEnum.MallOrderStatus.WaitingForDeliver.getType());
			orderGood.setPayTime(date);
			//优惠券金额大于订单金额的情况
			if(orderGood.getCouponCover()>orderGood.getGoodAmount()){
				orderGood.setCouponCover(orderGood.getGoodAmount());
			}

			//对订单进行冗余处理，添加订单的总原价，总现价，总会员价，总供货价
			OrderGoodItem orderGoodItem = new OrderGoodItem();
			orderGoodItem.setOrderId(orderGood.getId());
			List<OrderGoodItem> orderGoodItemList = orderGoodItemMapper.getOrderItemByOrderId(orderGoodItem);
			Integer OriginalPrice=0,PresentPrice=0,MemberPrice=0,SupplyPrice=0;//总的原价、现价、会员价、供货价
			if(orderGoodItemList != null && orderGoodItemList.size()>0){

				for(OrderGoodItem orderGoodItemListTemp:orderGoodItemList){
					Integer tempO = 0,tempP = 0,tempM = 0,tempS = 0;
					//如果订单详情中有商品的规格ID，就拿规格ID查找对应的规格的原价、现价、会员价、供货价，分别和商品总数相乘
					if(orderGoodItemListTemp.getGoodSpecId() != null){
						MallEntityGoodSpec mallEntityGoodSpec  = mallEntityGoodSpecMapper.selectByPrimaryKey(orderGoodItemListTemp.getGoodSpecId());
						tempO = mallEntityGoodSpec.getPrice4() * orderGoodItemListTemp.getGoodNum();//原价
						tempP = mallEntityGoodSpec.getPrice2() * orderGoodItemListTemp.getGoodNum();//现价
						tempM = mallEntityGoodSpec.getPrice() * orderGoodItemListTemp.getGoodNum();//会员价
						tempS = mallEntityGoodSpec.getPrice3() * orderGoodItemListTemp.getGoodNum();//供货价
					}else {
						//如果订单详情中没有商品的规格ID，就从商品表中取原价、现价、会员价、供货价，分别和商品总数相乘
						MallEntityGood mallEntityGood = mallEntityGoodMapper.selectByPrimaryKey(orderGoodItemListTemp.getGoodId());
						tempO = mallEntityGood.getSalePrice();//原价
						tempP = mallEntityGood.getPromotionPrice2();//现价
						tempM = mallEntityGood.getPromotionPrice();//会员价
						tempS = mallEntityGood.getSupplyPrice();//供货价
					}

					OriginalPrice += tempO;
					PresentPrice += tempP;
					MemberPrice += tempM;
					SupplyPrice += tempS;
				}

			}
			orderGood.setOriginalPrice(OriginalPrice);
			orderGood.setPresentPrice(PresentPrice);
			orderGood.setMemberPrice(MemberPrice);
			orderGood.setSupplyPrice(SupplyPrice);


			int j = orderGoodMapper.updateByPrimaryKeySelective(orderGood);

			logger.info("+>>>>>>>>>>>>>>核销积分优惠券>>>>>>>>>>>>>>>>>>>>>>>>>>>"+orderGood.getBonusCover());

			// 核销积分优惠券
			if (orderGood.getBonusCover() > 0) {

				bonusVerifyLogMapper.confirmBonusVerify(orderGood.getId());
				/**
				 * 更新订单号与
				 */
				BonusVerifyLog bonusVerifyLog = bonusVerifyLogMapper.queryBonusVerifyLog(orderGood.getId());
				bonusVerifyLog.setOrderId(tradeOffline.getId());
//				bonusVerifyLogMapper.updateByPrimaryKeySelective(bonusVerifyLog);
				//更新门店积分余额
//				if(shop !=null){
//					bonusVerifyShopMapper.updateShopBonusData(bonusVerifyLog.getAdjustAmount(),bonusVerifyLog.getShopId());
//				}

				if(shopid!=null && shopid !=0){
					//结算积分给门店 start
					Integer bonusamount = tradeOffline.getBonusAmount();
					Long groupId = tradeOffline.getGroupId();
					if(bonusamount != 0) {
						float settlerate = 0;
						//根据shopid获取积分结算规则
						BonusVerifyRule bonusVerifyRule = bonusVerifyRuleMapper.qyeryShopVerifyRule(shopid);
						if (bonusVerifyRule != null) {//如果有门店自定义的
							settlerate = bonusVerifyRule.getSettleRate();
						} else {//如果商圈给门店设置的
							bonusVerifyRule = bonusVerifyRuleMapper.selectBonusSettleRate(shopid, groupId);
							if (bonusVerifyRule != null) {
								settlerate = bonusVerifyRule.getSettleRate();
							} else {
								bonusVerifyRule = bonusVerifyRuleMapper.selectBonusVeriftyRuleByGroupId(groupId);
								if (bonusVerifyRule != null) {
									settlerate = bonusVerifyRule.getSettleRate();
								}
							}
						}

						//计算积分
						if (settlerate != 0) {
							int bonus = (int) (bonusamount * settlerate / 100);
							//积分结算给门店
							logger.info(">>>>>>>>>>>>>>>积分结算>>>>>>>>>>>>>>>>>>>>"+bonus);
							BonusVerifyShop result = bonusVerifyShopMapper.bonusShopVerify(groupId,shopid);
							if(result !=null){
								logger.info(">>>>>>>>>>>>>>>积分结算>>>>>>>>>>>>>>>>>>>>"+bonus);
								bonusVerifyShopMapper.updateShopVerifyBonus(groupId, shopid, bonus);
							}else{
								BonusVerifyShop bonusVerifyShop = new BonusVerifyShop();
								bonusVerifyShop.setGmtCreate(new Date());
								bonusVerifyShop.setGmtModified(new Date());
								bonusVerifyShop.setGroupId(groupId);
								bonusVerifyShop.setShopId(shopid);
								bonusVerifyShop.setAmount(bonus);
								bonusVerifyShop.setThisAmount(bonus);
								bonusVerifyShop.setVerifiedAmount(bonus);
								bonusVerifyShop.setStatus(1);
								bonusVerifyShopMapper.insertSelective(bonusVerifyShop);
							}


							//添加积分结算记录
							bonusVerifyLog.setSettingAmount(bonus);
							bonusVerifyLogMapper.updateByPrimaryKeySelective(bonusVerifyLog);

						}
					}
					//结算积分给门店 end

				}else{
					bonusVerifyLogMapper.updateByPrimaryKeySelective(bonusVerifyLog);
				}

				//更新会员的锁定积分金额
				memberMapper.updateActualConsumeBonus(orderGood.getMemberId(), orderGood.getBonusAmount());
			}
			if (orderGood.getCouponCover() > 0) {
				couponUserMapper.updateVerifyUserCouponByOrderId2(orderGood.getId());
				//跟新这个优惠券已核销张数
				CouponUser couponUser = couponUserMapper.queryCouponIdByTradeId(orderGood.getId());
				couponMapper.updateCouponInfo(couponUser.getCouponId());
			}

			if (j == 1) {
				if(tradeOffline.getRealAmount() > 0) {
//					String SysTraceNum = DateUtil.getSdfTimes() + Tools.getRandomNum(4);
//					PayConsumption payConsumption = PayConsumption.initialize(member.getVirtualCard(), payPwd, SysTraceNum, group.getPayGroupCode(),
//							orderId, payOrderId, tradeOffline.getRealAmount() + "", "156", null);
//					PayResult payResult = IPayAPI.consumption(payConsumption);


					 //查询钱包余额是否
					/*Boolean flag=memberService.updatequeryMemberBanal(member.getVirtualCard(), group.getPayGroupCode(), member.getUserId(),  tradeOffline.getRealAmount());
					if(flag==false){
						return Response.getError("钱包余额不足");
					}
*/
					logger.info("==========================去跟新本地钱包信息");
					PayResult payResult = posApiService.synUpdatePayConsumption(member.getVirtualCard(), group.getPayGroupCode(), member.getUserId(),  tradeOffline.getRealAmount(), orderId, payPwd,null,orderId);

//					PayResult payResult =walletService.updatePayConsumption(member.getVirtualCard(), group.getPayGroupCode(), member.getUserId(),
//							 tradeOffline.getRealAmount(), orderId, payPwd,null,orderId);
					if (!payResult.getRespCode().equals("0000")) {
						throw new ApplicationException(Rescode.FAIL, payResult.getMsgTxt());
					}

					if (payResult.getRespCode().equals("0000")) {
						TradeOffline finalTradeOffline = tradeOffline;
						exec.submit(new Runnable() {
							@Override
							public void run() {
								newBenefitCalc(shopid, finalTradeOffline.getRealAmount(), member.getGroupId(), member, finalTradeOffline.getId());
							}
						});

						try {
							memberService.insertMemberTradeDataAsyn(member.getId(), tradeOffline.getRealAmount(), tradeOffline.getBonusValue());
							templateMailSendService.sendTemplate(tradeOffline, BizEnum.WebTemplateType.template4.getType(), tradeOffline.getPayerId(),
									tradeOffline.getGroupId(), BizEnum.PaymentType.WebChat.getType(), payRootHomeURL);
						} catch (Exception e) {
							e.printStackTrace();
						}
						if(shopid!=null && shopid!=0) {//如果是商户商品，则进行推送
							//获取商户账号
							Userbase userbase = shopMapper.getUserNameByShopId(shopid);
							//发送推送信息
							Notice notice = new Notice();
							try {
								notice.setNoticetype(0);
								notice.setSender(member.getGroupId());
								notice.setReceiver(userbase.getUsername());
								notice.setNoticetitle("您有一笔新的订单");
								notice.setNoticetarget("ACCOUNT");
								notice.setNoticebody("您有一笔新的订单");
								notice.setGroupid(member.getGroupId());
								notice.setNoticestatus(1);
								notice.setIsplay(1);
								notice.setType(1);
								notice.setTvalue(orderGood.getId().toString());
								appNoticeService.sendNoticeToUsers(notice);
							} catch (Exception e) {
								e.printStackTrace();
							}
							//首单支付满
							try {
								int result = memberService.updateMemberFirstTradeSend(tradeOffline.getId(),tradeOffline.getPayerId(), tradeOffline.getGroupId(), tradeOffline.getRealAmount());
							}catch (Exception e) {
								e.printStackTrace();
							}

						}

						//结算和分润 start
						int profileamount = 0;
						//对供货价求和
						Long ordergoodid = orderGood.getId();
						int supplyprice = 0;

						List<OrderGoodItem> list = orderGoodItemMapper.listByOrderId(ordergoodid);
						for(int k = 0;k<list.size(); k++) {
							OrderGoodItem ogi = list.get(k);
							Long gsi = ogi.getGoodSpecId();
							Long goodid = ogi.getGoodId();
							if(gsi != null) {//有规格，查询该规格对应的供货价
								MallEntityGoodSpec megs = mallEntityGoodSpecMapper.selectByPrimaryKey(gsi);
								Integer supply_price = megs.getPrice3() * ogi.getGoodNum();
								supplyprice += supply_price;
							} else {//无规格，查询该商品对应的供货价
								MallEntityGood meg = mallEntityGoodMapper.selectByPrimaryKey(goodid);
								Integer supply_price = meg.getSupplyPrice() * ogi.getGoodNum();
								supplyprice += supply_price;
							}
						}

						//运费
						int freightcharge = orderGood.getFreightCharge();

						//计算交易手续费
						int ordertradefee = (int)((supplyprice + freightcharge) * Double.parseDouble(tradefee));

						//根据订单的供货价+运费-交易手续费进行计算结算金额
						int settleamount = supplyprice + freightcharge - ordertradefee;
						//如果是商户的商品则直接结算给商户
						if(shopid != null && shopid !=0) {
							//给商户增加冻结金额  结算天数 如果名店有设置 走门店没有走商圈的
							Shop result= shopMapper.selectByPrimaryKey(shopid);
							int day;
							if(result.getSettleDay()!=null){
								 day = result.getSettleDay();
							}else{
								day=group.getFreezeTime();
							}
//							walletService.updateLockedAmount(shop.getId()+"", "3", "+"+settleamount, "1", group.getFreezeTime(),orderId);
							walletService.updateLockedAmount(shop.getId()+"", "3", "+"+settleamount, "1", day,orderId);
						}

						//计算分润金额,分润金额=实付金额-供货价-运费
						profileamount = tradeOffline.getRealAmount() - (supplyprice + freightcharge);

						if(profileamount >= 0) {
							Map param = new HashMap();
							param.put("groupid", group.getId()+"");
							param.put("profileamount", profileamount+"");
							param.put("orderno", tradeOffline.getOrderId());
							exec.submit(new Runnable() {
								@Override
								public void run() {
									//调用分润接口
									HttpClientUtil.post(profiturl + "group/profile/computeEntityProfile", param);
								}
							});
						}
						//结算和分润 end

						return Response.buildSuccess("订单支付成功");
					} else if (payResult.getRespCode().equals("0009")) {
						throw new ApplicationException("账户余额不足");
					} else if (payResult.getRespCode().equals("008X")) {
						throw new ApplicationException("支付密码错误");
					}
				} else {
					try {
						memberService.insertMemberTradeDataAsyn(member.getId(), tradeOffline.getRealAmount(), tradeOffline.getBonusValue());
						templateMailSendService.sendTemplate(tradeOffline, BizEnum.WebTemplateType.template4.getType(), tradeOffline.getPayerId(),
								tradeOffline.getGroupId(), BizEnum.PaymentType.WebChat.getType(), payRootHomeURL);
					} catch (Exception e) {
						e.printStackTrace();
					}
					if(shopid!=null && shopid !=0) {//如果是商户商品，则进行推送
						//获取商户账号
						Userbase userbase = shopMapper.getUserNameByShopId(shopid);
						//发送推送信息
						Notice notice = new Notice();
						try {
							notice.setNoticetype(0);
							notice.setSender(member.getGroupId());
							notice.setReceiver(userbase.getUsername());
							notice.setNoticetitle("您有一笔新的订单");
							notice.setNoticetarget("ACCOUNT");
							notice.setNoticebody("您有一笔新的订单");
							notice.setGroupid(member.getGroupId());
							notice.setNoticestatus(1);
							notice.setIsplay(1);
							notice.setType(1);
							notice.setTvalue(orderGood.getId().toString());
							appNoticeService.sendNoticeToUsers(notice);
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
					try {
						int result = memberService.updateMemberFirstTradeSend(tradeOffline.getId(),tradeOffline.getPayerId(), tradeOffline.getGroupId(), tradeOffline.getRealAmount());


					}catch (Exception e) {

					}
					return Response.buildSuccess("订单支付成功");
				}
			}
		}
		throw new ApplicationException("订单支付失败");
	}

	@Override
	public Response saveWeixinPay(Long memberId, String orderId, String mchCreateIp,String notifyUrl) throws ApplicationException {
		Date date = new Date();
		Member member = memberMapper.selectByPrimaryKey(memberId);
		Group group = groupMapper.selectByPrimaryKey(member.getGroupId());
		GroupWxconfig groupWxconfig = groupWxconfigMapper.selectByGroupId(member.getGroupId());
		if (groupWxconfig == null) {
			return Response.getError("微信配置错误");
		}

		OrderGood orderGood = orderGoodMapper.selectOrderGoodInfo(orderId, BizEnum.MallOrderStatus.WaitingForPay.getType());
		if (orderGood == null) {
			return Response.getError("订单不存在");
		}
		Shop shop=null;
		if(orderGood.getShopId() !=null){
			//自营商品
			if(orderGood.getShopId()==0){

			}else{
				shop = shopMapper.selectByPrimaryKey(orderGood.getShopId());
			}
		}

	//	String merchantNo=group.getFyMerchantId();
		boolean flag = false;
		GroupReceiveInfo groupReceiveInfo = groupReceiveInfoMapper.selectMinReceiceInfo(group.getId());
		String merchantNo=groupReceiveInfo.getMerchantCode();
		TradeOffline tradeOffline = tradeOfflineMapper.selectByOrderId(orderId);
		if(tradeOffline == null) {
			tradeOffline = new TradeOffline();
			flag = true;
		}
		tradeOffline.setGmtCreate(date);
		tradeOffline.setGmtModified(date);
		tradeOffline.setGroupId(member.getGroupId());
		tradeOffline.setOrderId(orderId);
		tradeOffline.setPayerId(memberId);
		if(shop !=null){
			tradeOffline.setReceiverId(orderGood.getShopId().toString());
			tradeOffline.setReceiverName(shop.getMerchantName());
			tradeOffline.setReceiverType((byte) CommonEnum.UserType.Store.getType());
		}else{
			tradeOffline.setReceiverId(orderGood.getGroupId().toString());
			tradeOffline.setReceiverName(group.getMerchantName());
			tradeOffline.setReceiverType((byte) CommonEnum.UserType.BusinessManager.getType());
		}

		tradeOffline.setPayerName(member.getName());
		tradeOffline.setPayerType((byte) CommonEnum.UserType.User.getType());
		tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
		tradeOffline.setPayType((byte) BizEnum.PaymentType.WebChat.getType());
		tradeOffline.setSubType((byte) BizEnum.PaymentScene.Online.getType());
		tradeOffline.setOrderAmount(orderGood.getGoodAmount());

		//优惠券金额大于订单金额的情况
		if(orderGood.getCouponCover()>orderGood.getGoodAmount()){
			tradeOffline.setDiscountAmount(orderGood.getGoodAmount());
		}else{
			tradeOffline.setDiscountAmount(orderGood.getCouponCover());
		}
		tradeOffline.setBonusValue(orderGood.getBonusCover());
		tradeOffline.setBonusAmount(orderGood.getBonusAmount());
		tradeOffline.setMerchantNo(merchantNo);
		int realAmount = orderGood.getGoodAmount() + orderGood.getFreightCharge() - orderGood.getBonusCover() - orderGood.getCouponCover();
		realAmount = realAmount >= 0 ? realAmount : 0;
		tradeOffline.setRealAmount(realAmount);
		if(realAmount == 0) {
			tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
		} else {
			tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Failure.getType());
		}
		tradeOffline.setMemo("微信支付购买实物商品");
		tradeOffline.setPayOrderid(orderId);
		if(flag) {
			tradeOfflineMapper.insertSelective(tradeOffline);
		} else {
			tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
		}

		if(tradeOffline.getRealAmount() > 0) {

			WxTkPay wxTkPay = WxTkPay.initialize(tradeOffline.getRealAmount() + "", null,
					mchCreateIp, member.getPhone(), notifyUrl, merchantNo, "微信支付购买实物商品", "00000000", member.getOpenid(),orderId);

			WxTKPayResult wxTKPayResult = IPayAPI.finishWxTkPay(wxTkPay);

			logger.info("==========="+wxTKPayResult.getResult_code());
			if ("000000".equals(wxTKPayResult.getResult_code())) {
				Map<String, Object> data = new HashMap<>();
				data.put("status", 1);
				data.put("sdk_appid", wxTKPayResult.getSdk_appid());
				data.put("sdk_timestamp", wxTKPayResult.getSdk_timestamp());
				data.put("sdk_noncestr", wxTKPayResult.getSdk_noncestr());
				data.put("sdk_package", wxTKPayResult.getSdk_package());
				data.put("sdk_signtype", wxTKPayResult.getSdk_signtype());
				data.put("sdk_paysign", wxTKPayResult.getSdk_paysign());
				data.put("groupid", member.getGroupId());
				data.put("orderid", orderGood.getId());
				if(orderGood.getShopId()!=null&&orderGood.getShopId() != 0) {//如果是商户商品，则进行推送
					//获取商户账号
					Userbase userbase = shopMapper.getUserNameByShopId(orderGood.getShopId());
					data.put("shopaccount", userbase.getUsername());
				}

				/*System.out.print(":::::::::::::::事物商品收单消费满送::::::::::::::");
				//首单支付满
				try {
					logger.debug("=============首次消费送=============");
					int result = memberService.updateMemberFirstTradeSend(tradeOffline.getId(),tradeOffline.getPayerId(), tradeOffline.getGroupId(), tradeOffline.getRealAmount());
				}catch (Exception e) {

				}*/
				return Response.getSuccess(data);
			} else {
                Map<Object, Object> data2 = new HashMap<>();
                data2.put("status", 3);
                logger.info("======response====="+wxTKPayResult.getResult_code());
                Response response = Response.getError("支付失败");
                response.setResult(data2);
				return response;

			}
		} else {
			OrderGood orderGood1 = new OrderGood();
			orderGood1.setId(orderGood.getId());
			orderGood1.setStatus(BizEnum.MallOrderStatus.WaitingForDeliver.getType());
			//优惠金额大于订单金的时候吧订单优惠券金额修改为订单金额
			if(orderGood.getCouponCover()>orderGood.getGoodAmount()){
				orderGood1.setCouponCover(orderGood.getGoodAmount());
			}




			//对订单进行冗余处理，添加订单的总原价，总现价，总会员价，总供货价
			OrderGoodItem orderGoodItem = new OrderGoodItem();
			orderGoodItem.setOrderId(orderGood.getId());
			List<OrderGoodItem> orderGoodItemList = orderGoodItemMapper.getOrderItemByOrderId(orderGoodItem);
			Integer OriginalPrice=0,PresentPrice=0,MemberPrice=0,SupplyPrice=0;//总的原价、现价、会员价、供货价
			if(orderGoodItemList != null && orderGoodItemList.size()>0){

				for(OrderGoodItem orderGoodItemListTemp:orderGoodItemList){
					Integer tempO = 0,tempP = 0,tempM = 0,tempS = 0;
					//如果订单详情中有商品的规格ID，就拿规格ID查找对应的规格的原价、现价、会员价、供货价，分别和商品总数相乘
					if(orderGoodItemListTemp.getGoodSpecId() != null){
						MallEntityGoodSpec mallEntityGoodSpec  = mallEntityGoodSpecMapper.selectByPrimaryKey(orderGoodItemListTemp.getGoodSpecId());
						tempO = mallEntityGoodSpec.getPrice4() * orderGoodItemListTemp.getGoodNum();//原价
						tempP = mallEntityGoodSpec.getPrice2() * orderGoodItemListTemp.getGoodNum();//现价
						tempM = mallEntityGoodSpec.getPrice() * orderGoodItemListTemp.getGoodNum();//会员价
						tempS = mallEntityGoodSpec.getPrice3() * orderGoodItemListTemp.getGoodNum();//供货价
					}else{
						//如果订单详情中没有商品的规格ID，就从商品表中取原价、现价、会员价、供货价，分别和商品总数相乘
						MallEntityGood mallEntityGood = mallEntityGoodMapper.selectByPrimaryKey(orderGoodItemListTemp.getGoodId());
						tempO = mallEntityGood.getSalePrice();//原价
						tempP = mallEntityGood.getPromotionPrice2();//现价
						tempM = mallEntityGood.getPromotionPrice();//会员价
						tempS = mallEntityGood.getSupplyPrice();//供货价
					}

					OriginalPrice += tempO;
					PresentPrice += tempP;
					MemberPrice += tempM;
					SupplyPrice += tempS;
				}

			}
			orderGood1.setOriginalPrice(OriginalPrice);
			orderGood1.setPresentPrice(PresentPrice);
			orderGood1.setMemberPrice(MemberPrice);
			orderGood1.setSupplyPrice(SupplyPrice);




			orderGoodMapper.updateByPrimaryKeySelective(orderGood1);
			Map<String, Object> data = new HashMap<>();
			data.put("status", 2);
			data.put("groupid", member.getGroupId());
			data.put("orderid", orderGood.getId());
			if(orderGood.getShopId()!=null && orderGood.getShopId() != 0) {//如果是商户商品，则进行推送
				//获取商户账号
				Userbase userbase = shopMapper.getUserNameByShopId(orderGood.getShopId());
				data.put("shopaccount", userbase.getUsername());
			}


			//核销积分优惠券
			if (orderGood.getBonusAmount() > 0) {
				bonusVerifyLogMapper.confirmBonusVerify(orderGood.getId());

				/**
				 * 更新订单号与
				 */
				BonusVerifyLog bonusVerifyLog = bonusVerifyLogMapper.queryBonusVerifyLog(orderGood.getId());
				bonusVerifyLog.setOrderId(tradeOffline.getId());
//				bonusVerifyLogMapper.updateByPrimaryKeySelective(bonusVerifyLog);
				//更新门店积分余额
//				if (orderGood.getShopId() != null) {
//					bonusVerifyShopMapper.updateShopBonusData(bonusVerifyLog.getAdjustAmount(), bonusVerifyLog.getShopId());
//				}

               //积分结算到门店开始
                if(orderGood.getShopId() !=null && orderGood.getShopId() != 0){

                    //结算积分给门店 start
                    Integer bonusamount = tradeOffline.getBonusAmount();
                    Long groupId = tradeOffline.getGroupId();
                    if(bonusamount != 0) {
                        float settlerate = 0;
                        //根据shopid获取积分结算规则
                        BonusVerifyRule bonusVerifyRule = bonusVerifyRuleMapper.qyeryShopVerifyRule(orderGood.getShopId());
                        if (bonusVerifyRule != null) {//如果有门店自定义的
                            settlerate = bonusVerifyRule.getSettleRate();
                        } else {//如果商圈给门店设置的
                            bonusVerifyRule = bonusVerifyRuleMapper.selectBonusSettleRate(orderGood.getShopId(), groupId);
                            if (bonusVerifyRule != null) {
                                settlerate = bonusVerifyRule.getSettleRate();
                            } else {
                                bonusVerifyRule = bonusVerifyRuleMapper.selectBonusVeriftyRuleByGroupId(groupId);
                                if (bonusVerifyRule != null) {
                                    settlerate = bonusVerifyRule.getSettleRate();
                                }
                            }
                        }

                        //计算积分
                        if (settlerate != 0) {
                            int bonus = (int) (bonusamount * settlerate / 100);
                            //积分结算给门店
                            logger.info(">>>>>>>>>>>>>>>积分结算>>>>>>>>>>>>>>>>>>>>"+bonus);
                            BonusVerifyShop result = bonusVerifyShopMapper.bonusShopVerify(groupId,orderGood.getShopId());
                            if(result !=null){
                                logger.info(">>>>>>>>>>>>>>>积分结算>>>>>>>>>>>>>>>>>>>>"+bonus);
                                bonusVerifyShopMapper.updateShopVerifyBonus(groupId, orderGood.getShopId(), bonus);
                            }else{
                                BonusVerifyShop bonusVerifyShop = new BonusVerifyShop();
                                bonusVerifyShop.setGmtCreate(new Date());
                                bonusVerifyShop.setGmtModified(new Date());
                                bonusVerifyShop.setGroupId(groupId);
                                bonusVerifyShop.setShopId(orderGood.getShopId());
                                bonusVerifyShop.setAmount(bonus);
                                bonusVerifyShop.setThisAmount(bonus);
                                bonusVerifyShop.setVerifiedAmount(bonus);
                                bonusVerifyShop.setStatus(1);
                                bonusVerifyShopMapper.insertSelective(bonusVerifyShop);
                            }


                            //添加积分结算记录
                            bonusVerifyLog.setSettingAmount(bonus);
                            bonusVerifyLogMapper.updateByPrimaryKeySelective(bonusVerifyLog);

                        }


                    }
                    //结算积分给门店 end

                }else{
                    bonusVerifyLogMapper.updateByPrimaryKeySelective(bonusVerifyLog);
                }



				memberMapper.updateActualConsumeBonus(orderGood.getMemberId(), orderGood.getBonusAmount());
			}
			if (orderGood.getCouponCover() > 0) {
				couponUserMapper.updateVerifyUserCouponByOrderId2(orderGood.getId());
				CouponUser couponUser=couponUserMapper.queryCouponIdByTradeId(orderGood.getId());
				couponMapper.updateCouponInfo(couponUser.getCouponId());
			}
			try {
				//profitStatisService.saveOneOrderProfitCalculate(tradeOffline.getId());
				memberService.insertMemberTradeDataAsyn(orderGood.getMemberId(), tradeOffline.getRealAmount(), tradeOffline.getBonusValue());
			} catch (Exception e) {
				e.printStackTrace();
				throw new ApplicationException(Rescode.FAIL, "分润交易异常");
			}


			return Response.getSuccess(data);
		}
	}

	@Override
	public Response saveCardPay(Long memberId, String orderId, Long cardId, String merchantIp) throws ApplicationException {
		Date date = new Date();
		Member member = memberMapper.selectByPrimaryKey(memberId);
		Group group = groupMapper.selectByPrimaryKey(member.getGroupId());

		OrderGood orderGood = orderGoodMapper.selectOrderGoodInfo(orderId, BizEnum.MallOrderStatus.WaitingForPay.getType());
//		Long shopid=null;
//		if(orderGood.getShopId() !=null && orderGood.getShopId() !=0){
//			shopid = orderGood.getShopId();
//		}
		if (orderGood == null) {
			return Response.getError("订单不存在");
		}

		MemberCard memberCard = memberCardMapper.selectInfo(cardId, memberId);
		if (memberCard == null) {
			return Response.getError("银行卡信息不存在");
		}

		TradeOffline tradeOffline = new TradeOffline();
		tradeOffline.setGroupId(member.getGroupId());
		tradeOffline.setGmtCreate(date);
		tradeOffline.setGmtModified(date);
		tradeOffline.setGroupId(member.getGroupId());
		tradeOffline.setOrderId(orderId);
		tradeOffline.setPayerId(memberId);
		tradeOffline.setPayerName(member.getName());
		tradeOffline.setPayerType(((byte) CommonEnum.UserType.User.getType()));
		tradeOffline.setTransactionType((byte) BizEnum.TransactionType.Consumption.getType());
		tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.Success.getType());
		tradeOffline.setPayType((byte) BizEnum.PaymentType.NetBankCardQuick.getType());
		tradeOffline.setSubType((byte) BizEnum.PaymentScene.Online.getType());
		tradeOffline.setOrderAmount(orderGood.getGoodAmount());
		tradeOffline.setDiscountAmount(orderGood.getCouponCover());
		tradeOffline.setBonusValue(orderGood.getBonusCover());
		tradeOffline.setBonusAmount(orderGood.getBonusAmount());
		int realAmount = orderGood.getGoodAmount() + orderGood.getFreightCharge() - orderGood.getBonusCover() - orderGood.getCouponCover();
		realAmount = realAmount >= 0 ? realAmount : 0;
		tradeOffline.setRealAmount(realAmount);
		tradeOffline.setMemo("快捷卡支付购买实物商品");

		tradeOfflineMapper.insertSelective(tradeOffline);

		orderGood.setPayTime(date);
		orderGood.setStatus(BizEnum.MallOrderStatus.WaitingForDeliver.getType());



		//对订单进行冗余处理，添加订单的总原价，总现价，总会员价，总供货价
		OrderGoodItem orderGoodItem = new OrderGoodItem();
		orderGoodItem.setOrderId(orderGood.getId());
		List<OrderGoodItem> orderGoodItemList = orderGoodItemMapper.getOrderItemByOrderId(orderGoodItem);
		Integer OriginalPrice=0,PresentPrice=0,MemberPrice=0,SupplyPrice=0;//总的原价、现价、会员价、供货价
		if(orderGoodItemList != null && orderGoodItemList.size()>0){

			for(OrderGoodItem orderGoodItemListTemp:orderGoodItemList){
				Integer tempO = 0,tempP = 0,tempM = 0,tempS = 0;
				//如果订单详情中有商品的规格ID，就拿规格ID查找对应的规格的原价、现价、会员价、供货价，分别和商品总数相乘
				if(orderGoodItemListTemp.getGoodSpecId() != null){
					MallEntityGoodSpec mallEntityGoodSpec  = mallEntityGoodSpecMapper.selectByPrimaryKey(orderGoodItemListTemp.getGoodSpecId());
					tempO = mallEntityGoodSpec.getPrice4() * orderGoodItemListTemp.getGoodNum();//原价
					tempP = mallEntityGoodSpec.getPrice2() * orderGoodItemListTemp.getGoodNum();//现价
					tempM = mallEntityGoodSpec.getPrice() * orderGoodItemListTemp.getGoodNum();//会员价
					tempS = mallEntityGoodSpec.getPrice3() * orderGoodItemListTemp.getGoodNum();//供货价
				}else{
					//如果订单详情中没有商品的规格ID，就从商品表中取原价、现价、会员价、供货价，分别和商品总数相乘
					MallEntityGood mallEntityGood = mallEntityGoodMapper.selectByPrimaryKey(orderGoodItemListTemp.getGoodId());
					tempO = mallEntityGood.getSalePrice();//原价
					tempP = mallEntityGood.getPromotionPrice2();//现价
					tempM = mallEntityGood.getPromotionPrice();//会员价
					tempS = mallEntityGood.getSupplyPrice();//供货价
				}

				OriginalPrice += tempO;
				PresentPrice += tempP;
				MemberPrice += tempM;
				SupplyPrice += tempS;
			}

		}
		orderGood.setOriginalPrice(OriginalPrice);
		orderGood.setPresentPrice(PresentPrice);
		orderGood.setMemberPrice(MemberPrice);
		orderGood.setSupplyPrice(SupplyPrice);


		orderGoodMapper.updateByPrimaryKeySelective(orderGood);

		String cvnStr = null;
		if (memberCard.getCardType().equals(BizEnum.CardType.CreditCard.getType())) {
			cvnStr = memberCard.getCardCvn() + ";" + memberCard.getCardExpdate();
		}
		String orgOrderNum = UtilFun.createOrderNum();
		String payOrderid = Const.APP_RECHARGE + orgOrderNum;

		PayQuickPaymentRecharge payQuickPaymentRecharge = PayQuickPaymentRecharge.initialize(member.getPayGroupCode(), member.getVirtualCard(),
				tradeOffline.getRealAmount() + "", memberCard.getBankIntegral(), "156", memberCard.getIdName(), memberCard.getCardNum(), memberCard.getIdNo(),
				memberCard.getCardMobile(), "app快捷绑卡", DateUtil.fomatDate(date, DateUtil.sdfTimes), orgOrderNum, "1", payOrderid, cvnStr, merchantIp);
		PayResult payResult = IPayAPI.userQuickPaymentRecharge(payQuickPaymentRecharge);
		if (!PayResult.SUCCESS.equals(payResult.getRespCode())) {
			throw new ApplicationException(Rescode.FAIL, payResult.getMsgTxt());
		}

		Map<String, Object> data = new HashMap<>();
		data.put("cardId", memberCard.getId());
		data.put("tranAmt", tradeOffline.getRealAmount());
		return Response.getSuccess(data);
	}

	@Override
	public Response orderList(Long memberId, Integer orderStatus, Integer pageNo, Integer pageSize) {
		Integer pageStart = (pageNo - 1) * pageSize;
		List<OrderGood> orderGoodList = orderGoodMapper.listGoodsOrders(memberId, pageStart, orderStatus);
		for (OrderGood orderGood : orderGoodList) {
			Long shopid = orderGood.getShopId();
			if(shopid != null) {//由门店供货
				Shop shop = shopMapper.selectByPrimaryKey(shopid);
				orderGood.setContactPhone(shop.getPhone());
			} else {//由商圈供货
				Long groupid = orderGood.getGroupId();
				Group group = groupMapper.selectByPrimaryKey(groupid);
				orderGood.setContactPhone(group.getPrincipalMobile());
			}
			List<OrderGoodItem> orderGoodItemList = orderGoodItemMapper.listByOrderId(orderGood.getId());
			orderGood.setOrderGoodItemList(orderGoodItemList);
		}
		return Response.getSuccess(orderGoodList);
	}

	@Override
	public Map<String, Object> getCanUsedShopListByCouponId(Long couponId, String user_longitude, String user_latitude) throws Exception {
		if (couponId == null) {
			throw new ApplicationException(Rescode.FAIL, "couponId 不能为空！");
		}
		Map<String, Object> map = new HashMap<String, Object>();

		// 取得门店数据；
		List<Shop> shops = shopMapper.selectCanUsedShopListByCouponId(couponId);
		List<Map<String, Object>> shopList = new ArrayList<Map<String, Object>>();
		for (Shop shop : shops) {
			Map<String, Object> shopDetail = new HashMap<String, Object>();
			shopDetail.put("shop_id", shop.getId());
			shopDetail.put("shop_ico", shop.getIcon());
			shopDetail.put("shop_name", shop.getMerchantName());
			shopDetail.put("shop_score", shop.getShopScore());
			// shopDetail.put("shop_consume_average",shop.getShopScore());
			shopDetail.put("shop_type", shop.getIndustryName());

			String tolongitude = shop.getLongitude();
			String tolatitude = shop.getLatitude();
			long calDistance = -1;
			// if(StringUtil.notEmpty(user_longitude) &&
			// StringUtil.notEmpty(user_latitude)
			// && StringUtil.notEmpty(tolongitude)&&
			// StringUtil.notEmpty(tolatitude)){
			// calDistance =
			// QqMapApiHelper.getDistance(QqMapApiHelper.MODE_DRIVING,user_longitude,user_latitude,tolongitude,tolatitude);
			// }
			if (StringUtil.notEmpty(user_longitude) && StringUtil.notEmpty(user_latitude) && StringUtil.notEmpty(tolongitude)
					&& StringUtil.notEmpty(tolatitude)) {
				//
				calDistance = QqMapApiHelper.getDistance(QqMapApiHelper.MODE_DRIVING, user_latitude, user_longitude, tolatitude, tolongitude);
				if (calDistance > 0) {
					shopDetail.put("shop_location", calDistance);
				} else {
					double s = LocationUtils.getDistance(Double.parseDouble(user_latitude), Double.parseDouble(user_longitude), Double.parseDouble(tolatitude),
							Double.parseDouble(tolongitude));
					shopDetail.put("shop_location", (long) s);
				}
			} else {
				shopDetail.put("shop_location", calDistance);
			}
			shopList.add(shopDetail);
		}
		if (shopList.size() > 0) {
			map.put("shop_list", shopList);
		}

		return map;
	}

	@Override
	public Response getFreight(Long memberId, Long addressId, Long goodsId, Integer goodsNum, Long specId) {

		MallEntityGood mallEntityGood;
		if(specId != null) {
			mallEntityGood = mallEntityGoodMapper.selectBySpecId(specId);
		} else {
			mallEntityGood = mallEntityGoodMapper.selectByPrimaryKey(goodsId);
		}

		MemberAddress memberAddress = memberAddressMapper.selectByMemberIdAndId(memberId, addressId);
		String memberProvence = memberAddress.getCity().split(" ")[0].substring(0, 2);
		int memberProvenceId = citiesMapper.selectByName(memberProvence);
		MallFreightDetail mallFreightDetail = mallFreightDetailMapper.selectByFreightIdAndProvenceId(mallEntityGood.getPostMethod(), memberProvenceId);
		MallFreight mallFreight = mallFreightMapper.selectByPrimaryKey(mallEntityGood.getPostMethod());

		Map<String, Integer> data = new HashMap<>();
		if(mallFreightDetail != null) {//有自定义运费
			data.put("freightAmount", calFreight(mallEntityGood, goodsNum, mallFreightDetail, memberAddress, mallFreight, memberProvenceId ));
			data.put("freeAmount", mallFreightDetail == null ? null : mallFreightDetail.getFreeAmount());
			logger.info("=========有自定已运费freightAmount======"+calFreight(mallEntityGood, goodsNum, mallFreightDetail, memberAddress, mallFreight, memberProvenceId ));
			logger.info("=========有自定已运费freeAmount======"+mallFreightDetail == null ? null : mallFreightDetail.getFreeAmount());
		} else {//采用默认运费
            if(mallFreight != null) {
                if (mallFreight.getPricingManner() == 1) {//按件数
                    data.put("freightAmount", mallFreight.getFirstPrice() + (goodsNum - 1) * mallFreight.getAdditionPrice());

                    logger.info("按件数freightAmount"+mallFreight.getFirstPrice() + (goodsNum - 1) * mallFreight.getAdditionPrice());
                } else if (mallFreight.getPricingManner() == 2) {//按重量
                    data.put("freightAmount", mallFreight.getFirstPrice() + (int) (Math.ceil(((goodsNum * mallEntityGood.getWeight() - mallFreight.getFirstWeight()) / mallFreight.getAdditionWeight()))) * mallFreight.getAdditionPrice());

                    logger.info("按重量freightAmount"+mallFreight.getFirstPrice() + (int) (Math.ceil(((goodsNum * mallEntityGood.getWeight() - mallFreight.getFirstWeight()) / mallFreight.getAdditionWeight()))) * mallFreight.getAdditionPrice());
                }
				data.put("freeAmount", 0);
            }else {
				data.put("freightAmount", 0);
                data.put("freeAmount", 0);
            }

		}
		return Response.getSuccess(data);
	}

	@Override
	public Response goodReceived(Long memberId, Long orderId) {

		orderGoodMapper.updateGoodReceived(memberId, orderId);
		/*//计算分润
		OrderGood orderGood = orderGoodMapper.selectByPrimaryKey(orderId);
		String orderno = orderGood.getOrderNo();
		int groupid = orderGood.getGroupId().intValue();

		//计算供货价
		int sumprice = 0;
		List<OrderGoodItem> list = orderGoodItemMapper.listByOrderId(orderId);
		for(int i=0;i<list.size();i++) {
			OrderGoodItem ogi = list.get(i);
			int goodnum = ogi.getGoodNum();
			if(ogi.getGoodSpecId() != null) {
				MallEntityGoodSpec megs = mallEntityGoodSpecMapper.selectByPrimaryKey(ogi.getGoodSpecId());
				sumprice += goodnum * megs.getPrice3();
			} else {
				MallEntityGood meg = mallEntityGoodMapper.selectByPrimaryKey(ogi.getGoodId());
				sumprice += goodnum * meg.getSupplyPrice();
			}
		}


		TradeOffline tradeOffline = tradeOfflineMapper.selectOfflineByTradeNo(orderno);
		//实付金额
		int realamount = tradeOffline.getRealAmount();

		if(realamount-sumprice >= 0) {
			Map param = new HashMap();
			param.put("groupid", groupid+"");
			param.put("profileamount", (realamount-sumprice)+"");
			param.put("orderno", orderno);
			//调用分润接口
			HttpClientUtil.post(profiturl + "group/profile/computeEntityProfile", param);
		}
*/
		return Response.getSuccess("操作成功");
	}

	@Override
	public Response getFreightCart(Long memberId, Long addressId, ArrayList<Long> goodIds) {

		MemberAddress memberAddress = memberAddressMapper.selectByMemberIdAndId(memberId, addressId);
		String memberProvence = memberAddress.getCity().split(" ")[0].substring(0, 2);
		int memberProvenceId = citiesMapper.selectByName(memberProvence);

        Member member = memberMapper.selectByPrimaryKey(memberId);
        MemberGrade memberGrade = memberGradeMapper.queryMemberGrade(member.getGradeId());

		Map<String, Integer> data = new HashMap<>();
		int freightAmount = 0;
        int goodTotalAmount = 0;
        Integer freeAmount = 0;

		List<MallCart> mallCartList = mallCartMapper.listByMemberIdAndCartId(memberId, goodIds);
		for (MallCart mallCart : mallCartList) {
//			if (freightAmount > 0) {
//				int goodFreight = calFreight(memberId, addressId, mallCart.getGoodId(), mallCart.getGoodNumber());
//				if (goodFreight != 0) {
//					freightAmount += goodFreight;
//				} else {
//					freightAmount = 0;
//				}
//			}
			MallEntityGood mallEntityGood;
			if(mallCart.getSpecId() != null) {
				mallEntityGood = mallEntityGoodMapper.selectBySpecId(mallCart.getSpecId());
			} else {
				mallEntityGood = mallEntityGoodMapper.selectByPrimaryKey(mallCart.getGoodId());
			}

            int price;
            if(memberGrade.getName().equals(BizEnum.MemberGradeDefault.attention.getName())) {
                price = mallEntityGood.getPromotionPrice2();
            } else {
                price = mallEntityGood.getPromotionPrice();
            }

            //总金额和总数量
            goodTotalAmount += mallCart.getGoodNumber() * price;

			MallFreightDetail mallFreightDetail = mallFreightDetailMapper.selectByFreightIdAndProvenceId(mallEntityGood.getPostMethod(), memberProvenceId);
			MallFreight mallFreight = mallFreightMapper.selectByPrimaryKey(mallEntityGood.getPostMethod());
            if(mallFreightDetail != null&&mallFreightDetail.getFreeAmount() > freeAmount) {
				freeAmount = mallFreightDetail.getFreeAmount();
            } else {
                freeAmount = 0;
            }

			freightAmount += calFreight(mallEntityGood, mallCart.getGoodNumber(), mallFreightDetail, memberAddress, mallFreight, memberProvenceId);
		}

        if(freeAmount != null && freeAmount < goodTotalAmount) {
            freightAmount = 0;
        }

		data.put("freightAmount", freightAmount);
		return Response.getSuccess(data);
	}

//	private int calFreight(Long memberId, Long addressId, Long goodsId, Integer goodsNum, Long specId) {
	private int calFreight(MallEntityGood mallEntityGood, Integer goodsNum, MallFreightDetail mallFreightDetail, MemberAddress memberAddress,
						   MallFreight mallFreight, int memberProvenceId) {
        int freightAmount = 0;
//		MallEntityGood mallEntityGood;
//		if(specId != null) {
//			mallEntityGood = mallEntityGoodMapper.selectBySpecId(specId);
//		} else {
//			mallEntityGood = mallEntityGoodMapper.selectByPrimaryKey(goodsId);
//		}
        long postMethod = mallEntityGood.getPostMethod();
        int goodWeight = mallEntityGood.getWeight();
        if(postMethod != -2 && postMethod != -1) {
//            MemberAddress memberAddress = memberAddressMapper.selectByMemberIdAndId(memberId, addressId);
//            String memberProvence = memberAddress.getCity().split(" ")[0].substring(0, 2);
//            int memberProvenceId = citiesMapper.selectByName(memberProvence);
//            MallFreightDetail mallFreightDetail = mallFreightDetailMapper.selectByFreightIdAndProvenceId(mallEntityGood.getPostMethod(), memberProvenceId);
//            MallFreight mallFreight = mallFreightMapper.selectByPrimaryKey(mallEntityGood.getPostMethod());

            int firstPrice, additionPrice, firstWeight, additionWeight;
            if(mallFreightDetail == null) {
                firstPrice = mallFreight.getFirstPrice();
                additionPrice = mallFreight.getAdditionPrice();
                firstWeight = mallFreight.getFirstWeight();
                additionWeight = mallFreight.getAdditionWeight();
            } else {
                firstPrice = mallFreightDetail.getFirstPrice();
                additionPrice = mallFreightDetail.getAdditionPrice();
                firstWeight = mallFreightDetail.getFirstWeight();
                additionWeight = mallFreightDetail.getAdditionWeight();
            }

            if(mallFreight.getPricingManner() == 1) {//按件数
                int additionAmountMod = (goodsNum - firstWeight/1000) % (additionWeight/1000);
                int additionAmount = (goodsNum - firstWeight/1000) / (additionWeight/1000);
                if(additionAmountMod > 0) {
                    freightAmount = (additionAmount + 1) * additionPrice + firstPrice;
                } else {
                    freightAmount = (additionAmount < 0 ? 0 : additionAmount) * additionPrice  + firstPrice;
                }
				if(mallFreightDetail != null && mallFreightDetail.getFreeAmount()!=null) {
					//判断满多少免邮
					if (mallFreightDetail.getFreeAmount() <= mallEntityGood.getPromotionPrice() * goodsNum) {
						freightAmount = 0;
					}
				}
            } else if(mallFreight.getPricingManner() == 2) {//按重量
                int additionAmountMod = (goodWeight * goodsNum - firstWeight) % additionWeight;
                int additionAmount = (goodWeight * goodsNum - firstWeight) / additionWeight;
                if(additionAmountMod > 0) {
                    freightAmount = (additionAmount + 1) * additionPrice + firstPrice;
                } else {
                    freightAmount = (additionAmount < 0 ? 0 : additionAmount) * additionPrice + firstPrice;
                }

                if(mallFreightDetail != null && mallFreightDetail.getFreeAmount()!=null) {
					//判断满多少免邮
					if (mallFreightDetail.getFreeAmount() <= mallEntityGood.getPromotionPrice() * goodsNum) {
						freightAmount = 0;
					}
				}


            } else if(mallFreight.getPricingManner() == 3) {//按距离收费
				if(memberProvenceId == mallFreight.getWarehouseProvId()) {
					//根据地址获取收货地址的经纬度
					String address = memberAddress.getCity() + memberAddress.getArea();
					String result = HttpClientUtil.get(Const.GEOCODER + address.replaceAll(" ", ""));
					JSONObject jsonObj = JSONObject.parseObject(result);
					JSONObject resultObject = jsonObj.getJSONObject("result");
					JSONObject locationObject = resultObject.getJSONObject("location");//经纬度对象
					Double lng = locationObject.getDouble("lng");
					Double lat = locationObject.getDouble("lat");
					//计算收货地址和送货地址的距离
					Double resultdis = LocationUtils.getDistance(lat, lng, Double.parseDouble(mallFreight.getWarehouseLat()), Double.parseDouble(mallFreight.getWarehouseLng())) / 1000;
					System.out.println("距离。。。。。。。" + resultdis);
					//计算邮费
					if (resultdis.intValue() <= mallFreight.getFirstWeight() / 1000) {//首公里
						freightAmount = mallFreight.getFirstPrice();
					} else {//超出部门计算
						freightAmount = mallFreight.getFirstPrice() + (resultdis.intValue() - mallFreight.getFirstWeight() / 1000) / (mallFreight.getAdditionWeight() / 1000) * mallFreight.getAdditionPrice();
					}
				} else {
					freightAmount = -1;
				}
			}
        }
        return freightAmount;
    }


	@Override
	public Response orderRefund(Long memberId, Long orderId, Integer isReceivedGood, String refundReason, String picUrls) {
		int i = orderGoodMapper.memberOrderRefund(memberId, orderId, isReceivedGood, refundReason, picUrls);
		if (i == 1) {
			return Response.buildSuccess("操作成功");
		} else {
			return Response.getError("已申请退款，请不要重复操作");
		}
	}

	@Override
	public Response addressDetail(Long memberId, Long addressId) {
		MemberAddress memberAddress = memberAddressMapper.selectByMemberIdAndId(memberId, addressId);
		return Response.getSuccess(memberAddress);
	}

	// 查询线上优惠券可用商品列表
	@Override
	public Map<String, Object> queryGoodListByOnlineCouponId(Long couponId) throws Exception {
		int result = 0;
		Map<String, Object> map = new HashMap<String, Object>();
		if (couponId == null) {
			throw new ApplicationException(Rescode.FAIL, "couponId 不能为空！");
		}

		// result =
		// activityRedPackageService.insertRedpackageUser(memberId,redpackageUserId);
		Coupon coupon = couponMapper.selectByPrimaryKey(couponId);
		// 根据商品id列表查询商品列表
		List<MallEntityGood> mallEntityGoods = mallEntityGoodMapper.selectGoodListByGoodIds(coupon.getGroupId(), coupon.getShopids());
		List<Map<String, Object>> goodList = new ArrayList<Map<String, Object>>();
		for (MallEntityGood mallEntityGood : mallEntityGoods) {
			Map<String, Object> goodDetail = new HashMap<String, Object>();
			goodDetail.put("id", mallEntityGood.getId());
			goodDetail.put("goodName", mallEntityGood.getName());
			goodDetail.put("goodPic", mallEntityGood.getPicture().split(",")[0]);
			goodDetail.put("salePrice", mallEntityGood.getSalePrice());
			goodDetail.put("promotion_price", mallEntityGood.getPromotionPrice());
			goodDetail.put("promotion_price2", mallEntityGood.getPromotionPrice2());
			goodDetail.put("categoryFirstName", mallEntityGood.getCategoryFirstName());
			goodDetail.put("categorySecondName", mallEntityGood.getCategorySecondName());
			goodDetail.put("saleNum", mallEntityGood.getSaleNum());
			goodDetail.put("isLaunch", mallEntityGood.getIsLaunch());
			goodDetail.put("stockNumber", mallEntityGood.getStockNumber());
			goodList.add(goodDetail);
		}
		if (goodList.size() > 0) {
			map.put("good_List", goodList);
		}
		return map;
	}

	@Override
	public int insertCouponUser(String memberId, String goodId, Integer type)throws Exception {
		int result =0;
		if (Tools.isEmpty(memberId)) {
			throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
		}
		if (Tools.isEmpty(goodId)) {
			throw new ApplicationException(Rescode.FAIL, "goodId 不能为空！");
		}
		if (type == null) {
			throw new ApplicationException(Rescode.FAIL, "type 不能为空！");
		}
		Map<String, Object> map = new HashMap<String, Object>();

		// 根据商品id 获取优惠券id
		List<CouponGoodsShare> couponGoodsShareList = couponGoodsShareMapper.queryCuponIdByGoodId(Integer.parseInt(goodId), type);
		if (couponGoodsShareList.size()<=0) {
			return result;
		}

		for(CouponGoodsShare couponGoodsShare:couponGoodsShareList){
			result = couponUserService.sendOneMemberCoupon(Long.parseLong(memberId),couponGoodsShare.getCouponId(),
					null, ActivityEnum.RedPackageGetType.SharedGood.getType(), null);
		}

		return result;
	}

	@Override
	public Map<String, Object> addCouponUser(String memberId, String activityId) throws Exception {
		if (Tools.isEmpty(memberId)) {
			throw new ApplicationException(Rescode.FAIL, "memberId 不能为空！");
		}
		if (Tools.isEmpty(activityId)) {
			throw new ApplicationException(Rescode.FAIL, "activityId 不能为空！");
		}
		Map<String, Object> map = new HashMap<String, Object>();

		// 根据活动id获取优惠券id
		List<CouponActivityShare> couponActivityShareList = couponActivityShareMapper.queryCuponIdByActivityId(Long.parseLong(activityId));
		if (couponActivityShareList.size()<=0) {
			return map;
		}
		int result;
		int count=0;
		for(CouponActivityShare couponActivityShare:couponActivityShareList){
			result = couponUserService.sendOneMemberCoupon(Long.parseLong(memberId),couponActivityShare.getCouponId(),
					couponActivityShare.getActivityId(), ActivityEnum.RedPackageGetType.SharedGood.getType(), null);
			if(result==1){
				count +=1;
			}
		}
		map.put("count",count);

		return map;
	}

	@Override
	public void computeAmount(String orderNo) {

   		try {
			OrderGood orderGood = orderGoodMapper.selectByOrderNo(orderNo);
			TradeOffline tradeOffline = tradeOfflineMapper.selectByOrderId(orderNo);
			Group group = groupMapper.selectByPrimaryKey(orderGood.getGroupId());
			Long shopid = orderGood.getShopId();

			//结算和分润 start
			int profileamount = 0;

			//对供货价求和
			Long ordergoodid = orderGood.getId();
			int supplyprice = 0;

			List<OrderGoodItem> list = orderGoodItemMapper.listByOrderId(ordergoodid);
			for (int k = 0; k < list.size(); k++) {
				OrderGoodItem ogi = list.get(k);
				Long gsi = ogi.getGoodSpecId();
				Long goodid = ogi.getGoodId();
				if (gsi != null) {//有规格，查询该规格对应的供货价
					MallEntityGoodSpec megs = mallEntityGoodSpecMapper.selectByPrimaryKey(gsi);
					Integer supply_price = megs.getPrice3() * ogi.getGoodNum();
					supplyprice += supply_price;
				} else {//无规格，查询该商品对应的供货价
					MallEntityGood meg = mallEntityGoodMapper.selectByPrimaryKey(goodid);
					Integer supply_price = meg.getSupplyPrice() * ogi.getGoodNum();
					supplyprice += supply_price;
				}
			}

			//运费
			int freightcharge = orderGood.getFreightCharge();

			//计算交易手续费
			int ordertradefee = (int) ((supplyprice + freightcharge) * Double.parseDouble(tradefee));

			//根据订单的供货价+运费-交易手续费进行计算结算金额
			int settleamount = supplyprice + freightcharge - ordertradefee;
			//如果是商户的商品则直接结算给商户
			if (shopid != null && shopid != 0) {
				//给商户增加冻结金额 结算天数 门店有设置走门店 没有走商圈
				Shop result =shopMapper.selectByPrimaryKey(shopid);
				int day;
				if(result.getSettleDay() !=null){
					day =result.getSettleDay();
				}else{
					day =group.getFreezeTime();
				}
//				walletService.updateLockedAmount(shopid + "", "3", "+" + settleamount, "1", group.getFreezeTime(), orderNo);
				walletService.updateLockedAmount(shopid + "", "3", "+" + settleamount, "1", day, orderNo);
			}

			//计算分润金额,分润金额=实付金额-供货价-运费
			profileamount = tradeOffline.getRealAmount() - (supplyprice + freightcharge);

			if (profileamount >= 0) {
				Map param = new HashMap();
				param.put("groupid", group.getId() + "");
				param.put("profileamount", profileamount + "");
				param.put("orderno", tradeOffline.getOrderId());
				exec.submit(new Runnable() {
					@Override
					public void run() {
						//调用分润接口
						HttpClientUtil.post(profiturl + "group/profile/computeEntityProfile", param);
					}
				});
			}
			//结算和分润 end
		}catch (Exception e) {
   			e.printStackTrace();
		}
	}


}
